Compare commits
710 Commits
Author | SHA1 | Date | |
---|---|---|---|
160e630f03 | |||
13d19ff101 | |||
934babca85 | |||
95db646b3b | |||
f23d1d5d7c | |||
4334b45e82 | |||
ad1e09db55 | |||
2eb7f3ad2f | |||
5dd94c8298 | |||
412b44a981 | |||
9ffcc9e352 | |||
fe69ec7d6c | |||
045b67524c | |||
392572d684 | |||
3c07ba6b56 | |||
8c84c8b193 | |||
0321ddbb90 | |||
d74dd69329 | |||
7e85d5a954 | |||
da92601902 | |||
22458ad0be | |||
c8bc4386dd | |||
1e7cbd6358 | |||
30025c0241 | |||
7c50c068f5 | |||
ca4961a146 | |||
aef4dd3fe7 | |||
85f14f1c63 | |||
6a92c6af4e | |||
7115f7e61b | |||
62bc75af8a | |||
d763900b14 | |||
6acba9ab8f | |||
ca9f3bf8a9 | |||
c812363090 | |||
0a2701eef0 | |||
0d004bf6f3 | |||
450c608c83 | |||
053366c3e1 | |||
567fe74f10 | |||
cd62daccb0 | |||
29c775331a | |||
33d23dad6c | |||
42cf42fd8b | |||
e010940b61 | |||
46f7c5e565 | |||
6327cf7434 | |||
2c9a4d276a | |||
4dfba73e5c | |||
c282d662ca | |||
ca76e5cf0e | |||
b3d7594813 | |||
9d72bf2a36 | |||
a3a50f9c7b | |||
abc8ed4df0 | |||
643f1ae970 | |||
21a56ea36b | |||
a98749eb16 | |||
571c34f140 | |||
008ee613ab | |||
5999b6262d | |||
05b4a326de | |||
f036e06f6f | |||
5a27ebd1b3 | |||
a8646082a3 | |||
400be9a905 | |||
0582c608b3 | |||
92d9d03f99 | |||
b6653dd9b5 | |||
7a8af90b86 | |||
93d2cfa091 | |||
13012a9f89 | |||
afdcb6cfc7 | |||
c495d314d4 | |||
e877b68179 | |||
24ce6622a2 | |||
d77ef6a525 | |||
9ff1f5530e | |||
b3ea2ff8b6 | |||
4d9d8b28ec | |||
131e9d38b6 | |||
56e2c172e1 | |||
b3b7a393f8 | |||
dd9bdf4e2f | |||
7973491625 | |||
8df8f8cb08 | |||
fe76cbf31c | |||
7e2c6e5188 | |||
4502776513 | |||
edbc8ed972 | |||
9bab2c504e | |||
94b3c7e99a | |||
275cc7edf3 | |||
bd123dddc6 | |||
4a4b1bdb83 | |||
c6efa74a6b | |||
ae493f1084 | |||
ef915c94dc | |||
f4312cfa5a | |||
711b2bcf87 | |||
ac4cde1411 | |||
a45354fa08 | |||
2c0890854e | |||
bac04ab54b | |||
8c9e0b3884 | |||
fc8092f7cc | |||
30d4668008 | |||
02333a859a | |||
f9cc1cc363 | |||
7b7abf6973 | |||
8e5f01597e | |||
546f2fa739 | |||
8d0ae4284d | |||
b8d635a4b3 | |||
346d817dba | |||
3a9bbf6c73 | |||
fb7d340233 | |||
6a661bff0c | |||
d1dd21417b | |||
9ff32d9e29 | |||
d486ee467a | |||
20b66d9550 | |||
5abd03e241 | |||
359f8ffca3 | |||
46b9a1092d | |||
8fbf93ccc8 | |||
b866f06414 | |||
8b4f9a35f6 | |||
9683c297a7 | |||
8333815e95 | |||
d49871224c | |||
ba7bcce895 | |||
71e002c2ef | |||
f6c7281bb7 | |||
83bfe521b1 | |||
17c53b92b9 | |||
0b9022b868 | |||
5e0d4930cb | |||
b52d0c16e9 | |||
705e5098ab | |||
ac5c57ecef | |||
cd3b139c3f | |||
592b6a785e | |||
2f234cf6bc | |||
132a6a6a2f | |||
d876d6e74c | |||
b192238699 | |||
3b2ec3d880 | |||
03e4b5d525 | |||
a0221bf897 | |||
b1a639feae | |||
cfe7354c07 | |||
9732efe938 | |||
8f3385bbb6 | |||
d237b041b3 | |||
3cb87e083c | |||
8c6d0c6757 | |||
cb95326aca | |||
8679968ab0 | |||
204a72bbd3 | |||
7267c58913 | |||
14ae87fcd0 | |||
ee6fc12709 | |||
78e105f3b2 | |||
08607fb6b4 | |||
075d8ed094 | |||
b1bed7623d | |||
1401a82bb0 | |||
4524cf4418 | |||
0db15d46c3 | |||
08c43b8876 | |||
499beb7344 | |||
c9be614821 | |||
b56d35040d | |||
bd2ea2b917 | |||
e622d8dd38 | |||
d40e5e4fe6 | |||
1a7830f18e | |||
bcb301b730 | |||
ac9e5c6913 | |||
b515a4e270 | |||
325b7f455f | |||
ddf28dfe8b | |||
2680e8ffa3 | |||
2953772a0e | |||
ebbc9604ce | |||
a7aea12aa6 | |||
c6cceeb0c5 | |||
967932d02c | |||
81d5da51a3 | |||
fea9d1c5e2 | |||
df3a491d40 | |||
68753b4ae1 | |||
583b2a5ace | |||
13bd601cac | |||
3d5681cffd | |||
a1c2478e74 | |||
f1cf7e9269 | |||
4ce35870fe | |||
1996bef9e6 | |||
66cb0b1218 | |||
b9d470cf79 | |||
4f1fac02ab | |||
537b672fcf | |||
ced9749104 | |||
9aeb4c8cfe | |||
433d35e866 | |||
32d8f849ee | |||
8be1d5effb | |||
70c8605cca | |||
5b1a0a523f | |||
5f03238c8a | |||
b398f1e6f3 | |||
6f94d56383 | |||
fbda82218e | |||
b3cd4ebbd3 | |||
b0f83e401f | |||
f5806d9263 | |||
55600c49c9 | |||
beb88cc46f | |||
d49b38b00f | |||
85dc0b5527 | |||
0c79d1207e | |||
77a6a08192 | |||
1df5317e13 | |||
ae619e4163 | |||
738bd3b0dd | |||
400dc923e0 | |||
03be2512ca | |||
6ddd9e6fb8 | |||
9254d2411e | |||
5b7f0de48b | |||
a5b950a779 | |||
a2d59d6ef5 | |||
8ef5cdb8be | |||
c7b718f651 | |||
ff56e5c5de | |||
661c417fce | |||
b904ca0bcc | |||
fb836fe441 | |||
b23bc77001 | |||
16fcee802b | |||
48aef1829f | |||
4cc16e0136 | |||
7d20097465 | |||
a20b9a3960 | |||
e0d3f926b7 | |||
121bc910f6 | |||
4522cdc551 | |||
410772e81c | |||
0267b2efad | |||
c6d375eda2 | |||
847f41952e | |||
47044ec0d8 | |||
426ca36118 | |||
571d2a0075 | |||
1be09f5751 | |||
2663cb2e6e | |||
9b0bbb90ff | |||
83c9664c17 | |||
588645a2c3 | |||
1bfebd0d03 | |||
ac9e90c812 | |||
ba2fd00f01 | |||
3705996974 | |||
09299e5e5a | |||
09697b7679 | |||
4578b2c826 | |||
b3a293ab07 | |||
507ba16065 | |||
aa9f8a39a3 | |||
8d37220566 | |||
53e17a916b | |||
247dd84970 | |||
c2f3111922 | |||
44872300e9 | |||
91ed0118f6 | |||
a461c2306a | |||
46f4f84442 | |||
250a9f4f84 | |||
96e5a52651 | |||
5852245045 | |||
b4d93c4438 | |||
56dff65149 | |||
b4292d0972 | |||
d755383e39 | |||
e2c7b19000 | |||
8a488bab72 | |||
3afe3810bf | |||
dff1e8f1ce | |||
995aa7a8fc | |||
d7732f6ebc | |||
3ca5d17c40 | |||
244cb370a4 | |||
c35cb24bda | |||
b6ff08074c | |||
70d53fd45a | |||
f231a63e93 | |||
6091fcdfec | |||
bcfc15e398 | |||
045edc188c | |||
0778591524 | |||
d5e52bed43 | |||
06fdd3abe0 | |||
4e5898197a | |||
f96ebab99f | |||
3c54f99fea | |||
824f5bd731 | |||
3f3db8476e | |||
f375f080da | |||
e19e9ef5a4 | |||
682e65cb54 | |||
16a6d409d9 | |||
4186bcf1b2 | |||
df5112175f | |||
d9341a49ea | |||
4e9e4b6cde | |||
936b7012ba | |||
a9cbd9ec98 | |||
c9943fb857 | |||
a40274e2a2 | |||
b59d45c660 | |||
7b01e103c2 | |||
93a8acecce | |||
586bb91c0c | |||
baf03b81e3 | |||
9807e1189c | |||
3d5a0d9f73 | |||
cc96187f58 | |||
3aefa1d924 | |||
42e21b3733 | |||
0a35237915 | |||
a1f3a5ea26 | |||
e63f995258 | |||
d0c829c578 | |||
4ad9761b32 | |||
1f593d37fb | |||
109bfcb0f9 | |||
7ee49f5171 | |||
d759d16944 | |||
807d53c1e7 | |||
1355196b7c | |||
573316bcde | |||
784c28266c | |||
5da1b2a8aa | |||
0976d27cb1 | |||
6c83ff3496 | |||
f7f97ef625 | |||
5acdd72a1d | |||
f53686103d | |||
f63c9eb22f | |||
a37243cf30 | |||
b3c1b4a840 | |||
14bbf6eedc | |||
aa81193d5b | |||
9eb98e399d | |||
d48cfecf60 | |||
6036fb63ba | |||
cd48f69b1f | |||
fcc594ae26 | |||
f4de055aa1 | |||
35925cb3da | |||
ff430df845 | |||
e4cdea2111 | |||
b6ee47a541 | |||
b25009cde7 | |||
6fedd7ec84 | |||
9619c3fb20 | |||
02d029dd2d | |||
09c28e0355 | |||
3600077f3b | |||
de7656a787 | |||
5dfe7f8561 | |||
ed27898a33 | |||
532396d25c | |||
4b1b494164 | |||
0d33dc3eb9 | |||
994cbff215 | |||
bea2ee8bf2 | |||
1e5593f1a9 | |||
34febc4579 | |||
97581148b5 | |||
0402878daa | |||
4735f61fd1 | |||
16ae107e70 | |||
83efe2ae57 | |||
87e4d94290 | |||
b98e9ea202 | |||
9a62b1081d | |||
2cd1b890ce | |||
ba060bd0ee | |||
b1795b1e3d | |||
76c9820065 | |||
2db4ce57ef | |||
50b3d497f6 | |||
2321e9139d | |||
baabf21340 | |||
d3bb4c65a8 | |||
8c3e2a7559 | |||
bc52f8e4fd | |||
d3b14c325f | |||
4859b158b4 | |||
d65b51c62b | |||
a6444bb449 | |||
e09931dcf7 | |||
5bd189f2d0 | |||
8766287e72 | |||
10f9571c9e | |||
96a8259c42 | |||
68dd0622b8 | |||
558ac6b965 | |||
e773f95f21 | |||
314ce1c249 | |||
13275b1aa6 | |||
02d9169b5d | |||
7631bcc99e | |||
a32ee13fc9 | |||
b8ed738238 | |||
687c2a21cf | |||
ad18064e6b | |||
c9735ef75b | |||
b70882f01a | |||
5805334ccd | |||
c1b4382fe8 | |||
008743f20b | |||
50d778da3c | |||
8b7c731fd6 | |||
0b7918de9c | |||
4f61c04519 | |||
89cf06036d | |||
4ba6f248bc | |||
83a684c551 | |||
92a23f1eab | |||
622ac45258 | |||
791d203b5f | |||
77d6f9ae6f | |||
b1d9dfd6bf | |||
6532947e71 | |||
6c5f23f552 | |||
78c3034158 | |||
8f0098092d | |||
33a6579a3a | |||
b4221d4b74 | |||
0e4b9daaad | |||
ee72865f48 | |||
6521acf8f1 | |||
4f73410618 | |||
20eff200b1 | |||
ae1e1dc9f6 | |||
cf9e1545a4 | |||
6c7a8fffe0 | |||
3a3e2c05af | |||
02c7fd8d70 | |||
e6aa452b51 | |||
35449bfa17 | |||
acd51bbc90 | |||
f44cd9180c | |||
93c987a6cb | |||
3f0584ac09 | |||
59968fff1c | |||
7c62fe41b4 | |||
2781090405 | |||
14c9cf1b97 | |||
3dfff84cc3 | |||
5f3db72422 | |||
18bb285a90 | |||
60bad66bc3 | |||
99b34e8d8b | |||
9f1d85ab6e | |||
4323dd24d0 | |||
59bda1d547 | |||
1c760935f4 | |||
4f674755ce | |||
f1b792bd26 | |||
58c077b45e | |||
1854199c47 | |||
ecac8eb8e5 | |||
48cff50a4c | |||
fb628e9c62 | |||
2dece02df6 | |||
8f32e6a60f | |||
98614a1f3f | |||
c1b4c94b9c | |||
7ddbc12cdb | |||
1a217e21e9 | |||
147a7ce779 | |||
fb0289bb4c | |||
3e7970612a | |||
46244a6496 | |||
71d30e6654 | |||
008731c249 | |||
5628f97da1 | |||
8d0c6c6e66 | |||
5073c3cde8 | |||
3a27cfc4a1 | |||
3638b077cd | |||
646bd4eeb4 | |||
752f87a8dc | |||
b979ff0bc2 | |||
b085addbb0 | |||
94e0e4b000 | |||
7d51ab5846 | |||
41a9488cfa | |||
51b6b8521b | |||
e5379558f6 | |||
d1fd57c432 | |||
18603c9a46 | |||
5036f62a9c | |||
2047b8eda1 | |||
0e56c195bb | |||
2b33bfae6b | |||
3fc6d55003 | |||
8eddcd77bf | |||
27dd1d7944 | |||
b1cf2ec837 | |||
84f627f302 | |||
5c03613858 | |||
1825535abd | |||
2750c7ead0 | |||
3ccd7def86 | |||
65dab4e34f | |||
5591e15452 | |||
19f809b1c8 | |||
206767247e | |||
518354e7eb | |||
86dfb6562c | |||
c0a2473160 | |||
70a19b999d | |||
e54f51af81 | |||
b068466108 | |||
b562f28c1b | |||
230e01f078 | |||
082847b403 | |||
9471d80785 | |||
b263095533 | |||
14d5137703 | |||
d8a771916a | |||
f7f30d3406 | |||
b2c9cbb43e | |||
c733f80793 | |||
88d8f93793 | |||
e57a13ed7a | |||
23525ecc15 | |||
814bd05315 | |||
e81b88fb94 | |||
c4994d6429 | |||
0740d20ba0 | |||
9eaca6e4ab | |||
609869bf5a | |||
d68339cea7 | |||
0f4cdbf187 | |||
f3f8e7e52f | |||
8d07c1eb3e | |||
46edae9896 | |||
df0ab6aa8e | |||
7b48138ad0 | |||
e9032c55fa | |||
d75cb069d9 | |||
f69f635e0b | |||
8b5e511426 | |||
6641bf7c07 | |||
afc9f3f59a | |||
a55be58c01 | |||
dcf97ff5b4 | |||
72c0af9739 | |||
b0f9c6afa8 | |||
19bb0b655c | |||
26ce3e8814 | |||
aa207ec664 | |||
c626b988a6 | |||
82c387e92b | |||
14fb789002 | |||
9071351022 | |||
f688eda2c2 | |||
2810533df4 | |||
6b7144acce | |||
e68c0d088b | |||
2c0cc374d3 | |||
86d3d77a7f | |||
14a3ff32f6 | |||
50704eaeeb | |||
38458cc4d0 | |||
b19a49335f | |||
9dda932494 | |||
6ce7b6ef83 | |||
93ea037230 | |||
3f592988a9 | |||
96f490f84a | |||
37603735bd | |||
af40048841 | |||
3435c67e68 | |||
ecb9e4f57d | |||
dd61e8d19d | |||
eae06a4a7d | |||
0822b526d5 | |||
95e9ae2d8d | |||
29cf3ca0ef | |||
36716ca695 | |||
2334bafe68 | |||
bd4302e096 | |||
d8a1d88ded | |||
c427bc89ef | |||
4d7096f451 | |||
4525707048 | |||
b8267a69f6 | |||
ad53b42a68 | |||
93e0dbdc78 | |||
3e4bc9f85c | |||
8e10e67b89 | |||
3b0cc8548c | |||
e48ccdd4c8 | |||
e103040158 | |||
1948ea11ef | |||
6d375ac37e | |||
82a8c03953 | |||
207371aeae | |||
52cfa94652 | |||
65f4a35e7f | |||
e5284cf647 | |||
0a3595414e | |||
f4326daaa4 | |||
710cd5aed2 | |||
521a190b0f | |||
e22ff74e79 | |||
2c82a2bfc8 | |||
461e0a6873 | |||
d1fb442bd5 | |||
7c4a359a2b | |||
0cdc40beb3 | |||
4cd8b6f24f | |||
0f63682bdf | |||
52125a3992 | |||
06c9dfdb80 | |||
54386ccda3 | |||
d3c50cf89f | |||
50d2e082d5 | |||
c38469330d | |||
045c3a3ad4 | |||
904c354ee4 | |||
1a8a6d0b5d | |||
e0c8aed5c7 | |||
8f60d61ff9 | |||
5e6ab99403 | |||
8adcc4d83b | |||
b76737bdbb | |||
09f435d928 | |||
3dd9ea52d8 | |||
09917a2a95 | |||
96a4abf46c | |||
16e3090ee8 | |||
b3e10c05e6 | |||
112b3e5a6c | |||
60fdd82e2b | |||
9815010131 | |||
9875f8ea6e | |||
9e0bd62790 | |||
0d51877fcd | |||
e34090c39a | |||
5cc66e51db | |||
71f0a4e35e | |||
48a2013d9c | |||
6f3a654d6c | |||
0f7f0a9b1a | |||
d59e98dc83 | |||
b137a50d85 | |||
f75cd04181 | |||
b926f4cf09 | |||
5829c3d5be | |||
288afd1308 | |||
528fbd10e4 | |||
85128a634d | |||
f6acbaac7b | |||
b75da2c6d8 | |||
271ed2b9c1 | |||
1702e7ddb4 | |||
1fd8f690fe | |||
183e776970 | |||
f00dfdd34d | |||
0670275533 | |||
9e77c650d9 | |||
3497fdaf45 | |||
6077e825c5 | |||
0dd2a6dee5 | |||
c1b5e4f561 | |||
1a21c8ebfd | |||
f867f02546 | |||
7c6c147a18 | |||
0eff8516c0 | |||
34338e7107 | |||
57fdd223f1 | |||
bc3fc0c840 | |||
662038e40e | |||
53528f8275 | |||
1c792b46c9 | |||
2417cfda12 | |||
aa3516ca24 | |||
bcf5b21208 | |||
ba5eefb6dd | |||
407de7388c | |||
6adafde9a0 | |||
cba548114f | |||
016e7bd0b4 | |||
ad13ad8dba | |||
89168e6c96 | |||
a4b8e286db | |||
e837470a6a | |||
b589754485 | |||
0eccbb023c | |||
71a08ad8e2 | |||
0d4a999707 |
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
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
Normal file
6
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
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
Normal file
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
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
|
||||||
|
"
|
75
.github/workflows/build-windows-amd.yml
vendored
Normal file
75
.github/workflows/build-windows-amd.yml
vendored
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
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',$(git describe --tags --always)) | 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-windows-amd64.exe
|
||||||
|
$env:GOAMD64="v3"; $env:CGO_ENABLED=1; go build -tags build_actions -trimpath -ldflags '-w -s -buildid=' -o bin/clash-windows-amd64-v3.exe
|
||||||
|
|
||||||
|
cd bin/
|
||||||
|
Compress-Archive -Path clash-windows-amd64.exe -DestinationPath clash-plus-windows-amd64-$(git describe --tags --always)-$(Get-Date -Format 'yyyy.MM.dd').zip
|
||||||
|
Compress-Archive -Path clash-windows-amd64-v3.exe -DestinationPath clash-plus-windows-amd64-v3-$(git describe --tags --always)-$(Get-Date -Format 'yyyy.MM.dd').zip
|
||||||
|
Remove-Item -Force clash-windows-amd64.exe
|
||||||
|
Remove-Item -Force clash-windows-amd64-v3.exe
|
||||||
|
|
||||||
|
- name: Upload files to Artifacts
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
if: startsWith(github.ref, 'refs/tags/') == false
|
||||||
|
with:
|
||||||
|
name: clash-windows-amd64-${{ steps.test.outputs.file_sha }}-${{ steps.test.outputs.file_date }}
|
||||||
|
path: |
|
||||||
|
bin/*
|
||||||
|
|
||||||
|
- name: Delete workflow runs
|
||||||
|
uses: GitRML/delete-workflow-runs@main
|
||||||
|
with:
|
||||||
|
retain_days: 1
|
||||||
|
keep_minimum_runs: 2
|
29
.github/workflows/codeql-analysis.yml
vendored
Normal file
29
.github/workflows/codeql-analysis.yml
vendored
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
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
|
80
.github/workflows/docker.yml
vendored
Normal file
80
.github/workflows/docker.yml
vendored
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
name: Publish Docker Image
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- rm
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
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
Normal file
23
.github/workflows/linter.yml
vendored
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
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
|
120
.github/workflows/release.yml
vendored
Normal file
120
.github/workflows/release.yml
vendored
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
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
Normal file
19
.github/workflows/stale.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
|
||||||
|
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
|
11
.gitignore
vendored
11
.gitignore
vendored
@ -12,5 +12,14 @@ bin/*
|
|||||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||||
*.out
|
*.out
|
||||||
|
|
||||||
# dep
|
# go mod vendor
|
||||||
vendor
|
vendor
|
||||||
|
|
||||||
|
# GoLand
|
||||||
|
.idea/*
|
||||||
|
|
||||||
|
# macOS file
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# test suite
|
||||||
|
test/config/cache*
|
||||||
|
16
.golangci.yaml
Normal file
16
.golangci.yaml
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- gofumpt
|
||||||
|
- staticcheck
|
||||||
|
- govet
|
||||||
|
- gci
|
||||||
|
|
||||||
|
linters-settings:
|
||||||
|
gci:
|
||||||
|
sections:
|
||||||
|
- standard
|
||||||
|
- prefix(github.com/Dreamacro/clash)
|
||||||
|
- default
|
||||||
|
staticcheck:
|
||||||
|
go: '1.18'
|
26
.travis.yml
26
.travis.yml
@ -1,26 +0,0 @@
|
|||||||
language: go
|
|
||||||
sudo: false
|
|
||||||
go:
|
|
||||||
- '1.12'
|
|
||||||
install:
|
|
||||||
- "go mod download"
|
|
||||||
env:
|
|
||||||
global:
|
|
||||||
- NAME=clash
|
|
||||||
- BINDIR=bin
|
|
||||||
- GO111MODULE=on
|
|
||||||
script:
|
|
||||||
- go test ./...
|
|
||||||
before_deploy: make -j releases
|
|
||||||
deploy:
|
|
||||||
provider: releases
|
|
||||||
prerelease: true
|
|
||||||
skip_cleanup: true
|
|
||||||
api_key:
|
|
||||||
secure: dp1tc1h0er7aaAZ1hY0Xk/cUKwB0ifsAjg6e0M/Ad5NC87oucP6ESNFkDu0e9rUS1yB826/VnVGzNE/Z5zdjXVzPft+g5v5oRxzI4BKLhf07t9s+x8Z+3sApTxdsC5BvcN9x+5yRbpDLQ3biDPxSFu86j7m2pkEWw6XYNZO3/5y+RZXX7zu+d4MzTLUaA2kWl7KQAP0tEJNuw9ACDhpkw7LYbU/8q3E76prOTeme5/AT6Gxj7XhKUNP27lazhhqBSWM14ybPANqojNLEfMFHN/Eu2phYO07MuLTd4zuOIuw9y65kgvTFcHRlORjwUhnviXyA69obQejjgDI1WDOtU4PqpFaSLrxWtKI6k5VNWHARYggDm/wKl0WG7F0Kgio1KiGGhDg2yrbseXr/zBNaDhBtTFh6XJffqqwmgby1PXB6PWwfvWXooJMaQiFZczLWeMBl8v6XbSN6jtMTh/PQlKai6BcDd4LM8GQ7VHpSeff4qXEU4Vpnadjgs8VDPOHng6/HV+wDs8q2LrlMbnxLWxbCjOMUB6w7YnSrwH9owzKSoUs/531I4tTCRQIgipJtTK2b881/8osVjdMGS1mDXhBWO+OM0LCAdORJz+kN4PIkXXvKLt6jX74k6z4M3swFaqqtlTduN2Yy/ErsjguQO1VZfHmcpNssmJXI5QB9sxA=
|
|
||||||
file: bin/*
|
|
||||||
file_glob: true
|
|
||||||
on:
|
|
||||||
repo: Dreamacro/clash
|
|
||||||
branch: master
|
|
||||||
tags: true
|
|
21
Dockerfile
21
Dockerfile
@ -1,23 +1,18 @@
|
|||||||
FROM golang:latest as builder
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
RUN wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz -O /tmp/GeoLite2-Country.tar.gz && \
|
|
||||||
tar zxvf /tmp/GeoLite2-Country.tar.gz -C /tmp && \
|
|
||||||
mv /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /Country.mmdb
|
|
||||||
|
|
||||||
|
RUN apk add --no-cache make git && \
|
||||||
|
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
||||||
WORKDIR /clash-src
|
WORKDIR /clash-src
|
||||||
|
COPY --from=tonistiigi/xx:golang / /
|
||||||
COPY . /clash-src
|
COPY . /clash-src
|
||||||
|
|
||||||
RUN go mod download && \
|
RUN go mod download && \
|
||||||
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '-w -s' -o /clash
|
make docker && \
|
||||||
|
mv ./bin/clash-docker /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
|
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
|
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
COPY --from=builder /clash /
|
COPY --from=builder /clash /
|
||||||
|
|
||||||
EXPOSE 7890 7891
|
|
||||||
|
|
||||||
ENTRYPOINT ["/clash"]
|
ENTRYPOINT ["/clash"]
|
||||||
|
687
LICENSE
687
LICENSE
@ -1,21 +1,674 @@
|
|||||||
MIT License
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (c) 2018 Dreamacro
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Preamble
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
The GNU General Public License is a free, copyleft license for
|
||||||
copies or substantial portions of the Software.
|
software and other kinds of works.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
The licenses for most software and other practical works are designed
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
to take away your freedom to share and change the works. By contrast,
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
share and change all versions of a program--to make sure it remains free
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
GNU General Public License for most of our software; it applies also to
|
||||||
SOFTWARE.
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
120
Makefile
120
Makefile
@ -1,80 +1,70 @@
|
|||||||
|
GOCMD=go
|
||||||
|
XGOCMD=xgo -go=go-1.18.x
|
||||||
|
GOBUILD=CGO_ENABLED=1 $(GOCMD) build -trimpath
|
||||||
|
GOCLEAN=$(GOCMD) clean
|
||||||
NAME=clash
|
NAME=clash
|
||||||
BINDIR=bin
|
BINDIR=$(shell pwd)/bin
|
||||||
VERSION=$(shell git describe --tags || echo "unkown version")
|
VERSION=$(shell git describe --tags --always 2>/dev/null || date +%F)
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
BUILD_PACKAGE=.
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
RELEASE_LDFLAGS='-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-w -s'
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
|
-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 \
|
||||||
linux-386 \
|
darwin-arm64 \
|
||||||
linux-amd64 \
|
linux-amd64
|
||||||
linux-armv5 \
|
# linux-arm64
|
||||||
linux-armv6 \
|
# linux-386
|
||||||
linux-armv7 \
|
|
||||||
linux-armv8 \
|
|
||||||
linux-mips-softfloat \
|
|
||||||
linux-mips-hardfloat \
|
|
||||||
linux-mipsle \
|
|
||||||
linux-mips64 \
|
|
||||||
linux-mips64le \
|
|
||||||
freebsd-386 \
|
|
||||||
freebsd-amd64
|
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-amd64 \
|
||||||
windows-amd64
|
windows-386
|
||||||
|
# windows-arm64
|
||||||
|
|
||||||
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||||
|
|
||||||
|
local:
|
||||||
|
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
local-v3:
|
||||||
|
GOAMD64=v3 $(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=darwin-10.12/amd64 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-darwin-10.12-amd64 $(BINDIR)/$(NAME)-darwin-amd64
|
||||||
|
|
||||||
|
darwin-arm64:
|
||||||
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=darwin-11.1/arm64 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-darwin-11.1-arm64 $(BINDIR)/$(NAME)-darwin-arm64
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/386 $(BUILD_PACKAGE)
|
||||||
|
|
||||||
linux-amd64:
|
linux-amd64:
|
||||||
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -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-armv5:
|
linux-arm64:
|
||||||
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/arm64 $(BUILD_PACKAGE)
|
||||||
|
|
||||||
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-armv8:
|
|
||||||
GOARCH=arm64 GOOS=linux $(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:
|
|
||||||
GOARCH=mipsle 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)-$@
|
|
||||||
|
|
||||||
freebsd-386:
|
|
||||||
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
freebsd-amd64:
|
|
||||||
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows-6.0/386 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-windows-6.0-386.exe $(BINDIR)/$(NAME)-windows-386.exe
|
||||||
|
|
||||||
windows-amd64:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows-6.0/amd64 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-windows-6.0-amd64.exe $(BINDIR)/$(NAME)-windows-amd64.exe
|
||||||
|
|
||||||
|
#windows-arm64:
|
||||||
|
# $(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows/arm64 $(BUILD_PACKAGE)
|
||||||
|
# mv $(NAME)-windows-4.0-arm64.exe $(NAME)-windows-arm64.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))
|
||||||
@ -89,5 +79,19 @@ $(zip_releases): %.zip : %
|
|||||||
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
||||||
|
|
||||||
releases: $(gz_releases) $(zip_releases)
|
releases: $(gz_releases) $(zip_releases)
|
||||||
|
|
||||||
|
vet:
|
||||||
|
$(GOCMD) test -tags build_local ./...
|
||||||
|
|
||||||
|
lint:
|
||||||
|
golangci-lint run --build-tags=build_local ./...
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm -rf $(BINDIR)/
|
||||||
|
mkdir -p $(BINDIR)
|
||||||
|
|
||||||
|
cleancache:
|
||||||
|
# go build cache may need to cleanup if changing C source code
|
||||||
|
$(GOCLEAN) -cache
|
||||||
|
rm -rf $(BINDIR)/
|
||||||
|
mkdir -p $(BINDIR)
|
512
README.md
512
README.md
@ -6,233 +6,383 @@
|
|||||||
<h4 align="center">A rule-based tunnel in Go.</h4>
|
<h4 align="center">A rule-based tunnel in Go.</h4>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://travis-ci.org/Dreamacro/clash">
|
<a href="https://github.com/Dreamacro/clash/actions">
|
||||||
<img src="https://img.shields.io/travis/Dreamacro/clash.svg?style=flat-square"
|
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
||||||
alt="Travis-CI">
|
|
||||||
</a>
|
</a>
|
||||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
<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">
|
||||||
<a href="https://github.com/Dreamacro/clash/releases">
|
<a href="https://github.com/Dreamacro/clash/releases">
|
||||||
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
|
<a href="https://github.com/Dreamacro/clash/releases/tag/premium">
|
||||||
|
<img src="https://img.shields.io/badge/release-Premium-00b4f0?style=flat-square">
|
||||||
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- HTTP/HTTPS and SOCKS protocol
|
- Local HTTP/HTTPS/SOCKS server with authentication support
|
||||||
- Surge like configuration
|
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
||||||
- GeoIP rule support
|
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
||||||
- Support Vmess/Shadowsocks/Socks5
|
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
||||||
- Support for Netfilter TCP redirect
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node based off latency
|
||||||
|
- Remote providers, allowing users to get node lists remotely instead of hardcoding in config
|
||||||
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Install
|
## Getting Started
|
||||||
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
You can build from source:
|
## Advanced usage for this branch
|
||||||
|
### Build
|
||||||
|
This branch requires cgo and Python3.9, so make sure you set up Python3.9 before building.
|
||||||
|
|
||||||
```sh
|
For example, build on macOS:
|
||||||
go get -u -v github.com/Dreamacro/clash
|
```shell
|
||||||
|
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 cleancache && make local
|
||||||
|
# or make local-v3
|
||||||
|
|
||||||
|
ls bin/
|
||||||
|
|
||||||
|
# run
|
||||||
|
sudo bin/clash-local
|
||||||
```
|
```
|
||||||
|
|
||||||
Pre-built binaries are available: [release](https://github.com/Dreamacro/clash/releases)
|
### 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.
|
||||||
|
|
||||||
Requires Go >= 1.12.
|
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.
|
||||||
|
|
||||||
Checkout Clash version:
|
NOTE: this feature cannot work on tls pinning
|
||||||
|
|
||||||
```sh
|
WARNING: DO NOT USE THIS FEATURE TO BREAK LOCAL LAWS
|
||||||
clash -v
|
|
||||||
|
```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"'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Daemon
|
### DNS configuration
|
||||||
|
Support resolve ip with a proxy tunnel.
|
||||||
|
|
||||||
Unfortunately, there is no native elegant way to implement golang's daemon.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
So we can use third-party daemon tools like pm2, supervisor, and so on.
|
Use `curl -X POST controllerip:port/cache/fakeip/flush` to flush persistence fakeip
|
||||||
|
```yaml
|
||||||
|
dns:
|
||||||
|
enable: true
|
||||||
|
use-hosts: true
|
||||||
|
ipv6: false
|
||||||
|
enhanced-mode: fake-ip
|
||||||
|
fake-ip-range: 198.18.0.1/16
|
||||||
|
listen: 127.0.0.1:6868
|
||||||
|
default-nameserver:
|
||||||
|
- 119.29.29.29
|
||||||
|
- 114.114.114.114
|
||||||
|
nameserver:
|
||||||
|
- https://doh.pub/dns-query
|
||||||
|
- tls://223.5.5.5:853
|
||||||
|
fallback:
|
||||||
|
- 'https://1.0.0.1/dns-query#Proxy' # append the proxy adapter name to the end of DNS URL with '#' prefix.
|
||||||
|
- 'tls://8.8.4.4:853#Proxy'
|
||||||
|
fallback-filter:
|
||||||
|
geoip: false
|
||||||
|
geosite:
|
||||||
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to untrusted DNS providers.
|
||||||
|
domain:
|
||||||
|
- +.example.com
|
||||||
|
ipcidr:
|
||||||
|
- 0.0.0.0/32
|
||||||
|
```
|
||||||
|
|
||||||
In the case of [pm2](https://github.com/Unitech/pm2), we can start the daemon this way:
|
### TUN configuration
|
||||||
|
Supports macOS, Linux and Windows.
|
||||||
|
|
||||||
```sh
|
On Windows, you should download the [Wintun](https://www.wintun.net) driver and copy `wintun.dll` into the system32 directory.
|
||||||
pm2 start clash
|
```yaml
|
||||||
|
# Enable the TUN listener
|
||||||
|
tun:
|
||||||
|
enable: true
|
||||||
|
stack: gvisor # System or gVisor
|
||||||
|
# device: tun://utun8 # or fd://xxx, it's optional
|
||||||
|
dns-hijack:
|
||||||
|
- 0.0.0.0:53 # hijack all public
|
||||||
|
auto-route: true # auto set global route
|
||||||
|
```
|
||||||
|
### Rules configuration
|
||||||
|
- Support rule `GEOSITE`.
|
||||||
|
- Support rule `USER-AGENT`.
|
||||||
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
|
- Support `network` condition for all rules.
|
||||||
|
- Support `process` condition for all rules.
|
||||||
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
|
|
||||||
|
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
|
||||||
|
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'
|
||||||
|
|
||||||
|
rules:
|
||||||
|
# rule SCRIPT
|
||||||
|
- SCRIPT,quic,REJECT # Disable QUIC, same as rule "DST-PORT,443,REJECT,udp"
|
||||||
|
- SCRIPT,privacy,REJECT
|
||||||
|
|
||||||
|
# network condition for all rules
|
||||||
|
- DOMAIN-SUFFIX,example.com,DIRECT,tcp
|
||||||
|
- DOMAIN-SUFFIX,example.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
|
||||||
|
- 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
|
||||||
|
- GEOSITE,category-ads-all,REJECT
|
||||||
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
|
- GEOSITE,apple@cn,DIRECT
|
||||||
|
- GEOSITE,apple-cn,DIRECT
|
||||||
|
- GEOSITE,microsoft@cn,DIRECT
|
||||||
|
- GEOSITE,facebook,PROXY
|
||||||
|
- GEOSITE,youtube,PROXY
|
||||||
|
- GEOSITE,geolocation-cn,DIRECT
|
||||||
|
- GEOSITE,geolocation-!cn,PROXY
|
||||||
|
|
||||||
|
# source IPCIDR condition for all rules in gateway proxy
|
||||||
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
|
- GEOIP,lan,DIRECT,no-resolve
|
||||||
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
If you have Docker installed, you can run clash directly using `docker-compose`.
|
### Script configuration
|
||||||
|
Script enables users to programmatically select a policy for the packets with more flexibility.
|
||||||
|
|
||||||
[Run clash in docker](https://github.com/Dreamacro/clash/wiki/Run-clash-in-docker)
|
```yaml
|
||||||
|
mode: script
|
||||||
|
|
||||||
## Config
|
rules:
|
||||||
|
# the rule GEOSITE just as a rule provider in mode script
|
||||||
|
- GEOSITE,category-ads-all,Whatever
|
||||||
|
- GEOSITE,youtube,Whatever
|
||||||
|
- GEOSITE,geolocation-cn,Whatever
|
||||||
|
|
||||||
|
script:
|
||||||
|
code: |
|
||||||
|
def main(ctx, metadata):
|
||||||
|
if metadata["process_name"] == 'apsd':
|
||||||
|
return "DIRECT"
|
||||||
|
|
||||||
The default configuration directory is `$HOME/.config/clash`
|
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"
|
||||||
|
|
||||||
The name of the configuration file is `config.yml`
|
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"
|
||||||
|
|
||||||
If you want to use another directory, you can use `-d` to control the configuration directory
|
code = ctx.geoip(ip)
|
||||||
|
if code == "LAN" or code == "CN":
|
||||||
|
return "DIRECT"
|
||||||
|
|
||||||
For example, you can use the current directory as the configuration directory
|
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
|
||||||
|
}
|
||||||
|
|
||||||
```sh
|
interface Context {
|
||||||
clash -d .
|
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 }>
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Below is a simple demo configuration file:
|
### Proxies configuration
|
||||||
|
Support outbound protocol `VLESS`.
|
||||||
|
|
||||||
```yml
|
Support `Trojan` with XTLS.
|
||||||
# port of HTTP
|
|
||||||
port: 7890
|
|
||||||
|
|
||||||
# port of SOCKS5
|
Currently XTLS only supports TCP transport.
|
||||||
socks-port: 7891
|
```yaml
|
||||||
|
proxies:
|
||||||
# redir port for Linux and macOS
|
# VLESS
|
||||||
# redir-port: 7892
|
- name: "vless-tls"
|
||||||
|
type: vless
|
||||||
allow-lan: false
|
server: server
|
||||||
|
port: 443
|
||||||
# Rule / Global/ Direct (default is Rule)
|
uuid: uuid
|
||||||
mode: Rule
|
network: tcp
|
||||||
|
servername: example.com
|
||||||
# set log level to stdout (default is info)
|
udp: true
|
||||||
# info / warning / error / debug / silent
|
# skip-cert-verify: true
|
||||||
log-level: info
|
- name: "vless-xtls"
|
||||||
|
type: vless
|
||||||
# A RESTful API for clash
|
server: server
|
||||||
external-controller: 127.0.0.1:9090
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
# you can put the static web resource (such as clash-dashboard) to a directory, and clash would serve in `${API}/ui`
|
network: tcp
|
||||||
# input is a relative path to the configuration directory or an absolute path
|
servername: example.com
|
||||||
# external-ui: folder
|
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||||
|
# flow-show: true # print the XTLS direction log
|
||||||
# Secret for RESTful API (Optional)
|
# udp: true
|
||||||
# secret: ""
|
|
||||||
|
|
||||||
# experimental feature
|
|
||||||
experimental:
|
|
||||||
ignore-resolve-fail: true # ignore dns reslove fail, default value is true
|
|
||||||
|
|
||||||
# dns:
|
|
||||||
# enable: true # set true to enable dns (default is false)
|
|
||||||
# ipv6: false # default is false
|
|
||||||
# listen: 0.0.0.0:53
|
|
||||||
# enhanced-mode: redir-host # or fake-ip
|
|
||||||
# # fake-ip-range: 198.18.0.1/16 # if you don't know what it is, don't change it
|
|
||||||
# nameserver:
|
|
||||||
# - 114.114.114.114
|
|
||||||
# - tls://dns.rubyfish.cn:853 # dns over tls
|
|
||||||
# fallback: # concurrent request with nameserver, fallback used when GEOIP country isn't CN
|
|
||||||
# - tcp://1.1.1.1
|
|
||||||
|
|
||||||
Proxy:
|
|
||||||
|
|
||||||
# shadowsocks
|
|
||||||
# The types of cipher are consistent with go-shadowsocks2
|
|
||||||
# support AEAD_AES_128_GCM AEAD_AES_192_GCM AEAD_AES_256_GCM AEAD_CHACHA20_POLY1305 AES-128-CTR AES-192-CTR AES-256-CTR AES-128-CFB AES-192-CFB AES-256-CFB CHACHA20-IETF XCHACHA20
|
|
||||||
# In addition to what go-shadowsocks2 supports, it also supports chacha20 rc4-md5 xchacha20-ietf-poly1305
|
|
||||||
- { name: "ss1", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password", udp: true }
|
|
||||||
|
|
||||||
# old obfs configuration remove after prerelease
|
|
||||||
- name: "ss2"
|
|
||||||
type: ss
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
cipher: AEAD_CHACHA20_POLY1305
|
|
||||||
password: "password"
|
|
||||||
plugin: obfs
|
|
||||||
plugin-opts:
|
|
||||||
mode: tls # or http
|
|
||||||
# host: bing.com
|
|
||||||
|
|
||||||
- name: "ss3"
|
|
||||||
type: ss
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
cipher: AEAD_CHACHA20_POLY1305
|
|
||||||
password: "password"
|
|
||||||
plugin: v2ray-plugin
|
|
||||||
plugin-opts:
|
|
||||||
mode: websocket # no QUIC now
|
|
||||||
# tls: true # wss
|
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
# host: bing.com
|
|
||||||
# path: "/"
|
|
||||||
# headers:
|
|
||||||
# custom: value
|
|
||||||
|
|
||||||
# vmess
|
# Trojan
|
||||||
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
- name: "trojan-xtls"
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto }
|
type: trojan
|
||||||
# with tls
|
server: server
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true }
|
port: 443
|
||||||
# with tls and skip-cert-verify
|
password: yourpsk
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true, skip-cert-verify: true }
|
network: tcp
|
||||||
# with ws-path and ws-headers
|
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path, ws-headers: { Host: v2ray.com } }
|
# flow-show: true # print the XTLS direction log
|
||||||
# with ws + tls
|
# udp: true
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path, tls: true }
|
# sni: example.com # aka server name
|
||||||
|
# skip-cert-verify: true
|
||||||
# socks5
|
|
||||||
- { name: "socks", type: socks5, server: server, port: 443 }
|
|
||||||
# socks5 with authentication
|
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, username: "username", password: "password" }
|
|
||||||
# with tls
|
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, tls: true }
|
|
||||||
# with tls and skip-cert-verify
|
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, tls: true, skip-cert-verify: true }
|
|
||||||
|
|
||||||
# http
|
|
||||||
- { name: "http", type: http, server: server, port: 443 }
|
|
||||||
# http with authentication
|
|
||||||
- { name: "http", type: http, server: server, port: 443, username: "username", password: "password" }
|
|
||||||
# with tls (https)
|
|
||||||
- { name: "http", type: http, server: server, port: 443, tls: true }
|
|
||||||
# with tls (https) and skip-cert-verify
|
|
||||||
- { name: "http", type: http, server: server, port: 443, tls: true, skip-cert-verify: true }
|
|
||||||
|
|
||||||
Proxy Group:
|
|
||||||
# url-test select which proxy will be used by benchmarking speed to a URL.
|
|
||||||
- { name: "auto", type: url-test, proxies: ["ss1", "ss2", "vmess1"], url: "http://www.gstatic.com/generate_204", interval: 300 }
|
|
||||||
|
|
||||||
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
|
||||||
- { name: "fallback-auto", type: fallback, proxies: ["ss1", "ss2", "vmess1"], url: "http://www.gstatic.com/generate_204", interval: 300 }
|
|
||||||
|
|
||||||
# load-balance: The request of the same eTLD will be dial on the same proxy.
|
|
||||||
- { name: "load-balance", type: load-balance, proxies: ["ss1", "ss2", "vmess1"], url: "http://www.gstatic.com/generate_204", interval: 300 }
|
|
||||||
|
|
||||||
# select is used for selecting proxy or proxy group
|
|
||||||
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
|
||||||
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
|
|
||||||
|
|
||||||
Rule:
|
|
||||||
- DOMAIN-SUFFIX,google.com,auto
|
|
||||||
- DOMAIN-KEYWORD,google,auto
|
|
||||||
- DOMAIN,google.com,auto
|
|
||||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
|
||||||
- IP-CIDR,127.0.0.0/8,DIRECT
|
|
||||||
# rename SOURCE-IP-CIDR and would remove after prerelease
|
|
||||||
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
|
||||||
- GEOIP,CN,DIRECT
|
|
||||||
- DST-PORT,80,DIRECT
|
|
||||||
- SRC-PORT,7777,DIRECT
|
|
||||||
# FINAL would remove after prerelease
|
|
||||||
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
|
||||||
- MATCH,auto
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Documentations
|
### IPTABLES configuration
|
||||||
https://clash.gitbook.io/
|
Work on Linux OS who's supported `iptables`
|
||||||
|
|
||||||
## Thanks
|
```yaml
|
||||||
|
# Enable the TPROXY listener
|
||||||
|
tproxy-port: 9898
|
||||||
|
|
||||||
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
iptables:
|
||||||
|
enable: true # default is false
|
||||||
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
|
```
|
||||||
|
Run Clash as a daemon.
|
||||||
|
|
||||||
[v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
||||||
|
```shell
|
||||||
|
[Unit]
|
||||||
|
Description=Clash daemon, A rule-based proxy in Go.
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
CapabilityBoundingSet=cap_net_admin
|
||||||
|
Restart=always
|
||||||
|
ExecStart=/usr/local/bin/clash -d /etc/clash
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
Launch clashd on system startup with:
|
||||||
|
```shell
|
||||||
|
$ systemctl enable clash
|
||||||
|
```
|
||||||
|
Launch clashd immediately with:
|
||||||
|
```shell
|
||||||
|
$ systemctl start clash
|
||||||
|
```
|
||||||
|
|
||||||
|
### Display Process name
|
||||||
|
To display process name online by click [https://yaling888.github.io/yacd/](https://yaling888.github.io/yacd/).
|
||||||
|
|
||||||
|
You can download the [Dashboard](https://github.com/yaling888/yacd/archive/gh-pages.zip) into Clash home directory:
|
||||||
|
```shell
|
||||||
|
cd ~/.config/clash
|
||||||
|
curl -LJ https://github.com/yaling888/yacd/archive/gh-pages.zip -o dashboard.zip
|
||||||
|
unzip dashboard.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
Add to config file:
|
||||||
|
```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)
|
||||||
|
|
||||||
|
## Development
|
||||||
|
If you want to build an application that uses clash as a library, check out the the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
This software is released under the GPL-3.0 license.
|
||||||
|
|
||||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
||||||
|
|
||||||
## TODO
|
|
||||||
|
|
||||||
- [x] Complementing the necessary rule operators
|
|
||||||
- [x] Redir proxy
|
|
||||||
- [x] UDP support
|
|
||||||
- [ ] Connection manager
|
|
||||||
|
197
adapter/adapter.go
Normal file
197
adapter/adapter.go
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
package adapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
_ "unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:linkname errCanceled net.errCanceled
|
||||||
|
var errCanceled error
|
||||||
|
|
||||||
|
type Proxy struct {
|
||||||
|
C.ProxyAdapter
|
||||||
|
history *queue.Queue[C.DelayHistory]
|
||||||
|
alive *atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alive implements C.Proxy
|
||||||
|
func (p *Proxy) Alive() bool {
|
||||||
|
return p.alive.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial implements C.Proxy
|
||||||
|
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||||
|
defer cancel()
|
||||||
|
return p.DialContext(ctx, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
||||||
|
p.alive.Store(err == nil || errors.Is(err, errCanceled))
|
||||||
|
return conn, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultUDPTimeout)
|
||||||
|
defer cancel()
|
||||||
|
return p.ListenPacketContext(ctx, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
|
p.alive.Store(err == nil)
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DelayHistory implements C.Proxy
|
||||||
|
func (p *Proxy) DelayHistory() []C.DelayHistory {
|
||||||
|
queueM := p.history.Copy()
|
||||||
|
histories := []C.DelayHistory{}
|
||||||
|
for _, item := range queueM {
|
||||||
|
histories = append(histories, item)
|
||||||
|
}
|
||||||
|
return histories
|
||||||
|
}
|
||||||
|
|
||||||
|
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
||||||
|
// implements C.Proxy
|
||||||
|
func (p *Proxy) LastDelay() (delay uint16) {
|
||||||
|
var max uint16 = 0xffff
|
||||||
|
if !p.alive.Load() {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
history := p.history.Last()
|
||||||
|
if history.Delay == 0 {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
return history.Delay
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||||
|
inner, err := p.ProxyAdapter.MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return inner, err
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping := map[string]any{}
|
||||||
|
_ = json.Unmarshal(inner, &mapping)
|
||||||
|
mapping["history"] = p.DelayHistory()
|
||||||
|
mapping["name"] = p.Name()
|
||||||
|
mapping["udp"] = p.SupportUDP()
|
||||||
|
return json.Marshal(mapping)
|
||||||
|
}
|
||||||
|
|
||||||
|
// URLTest get the delay for the specified URL
|
||||||
|
// implements C.Proxy
|
||||||
|
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||||
|
defer func() {
|
||||||
|
p.alive.Store(err == nil)
|
||||||
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
|
if err == nil {
|
||||||
|
record.Delay = t
|
||||||
|
}
|
||||||
|
p.history.Put(record)
|
||||||
|
if p.history.Len() > 10 {
|
||||||
|
p.history.Pop()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
addr, err := urlToMetadata(url)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
instance, err := p.DialContext(ctx, &addr)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = instance.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodHead, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||||
|
return instance, nil
|
||||||
|
},
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{
|
||||||
|
Transport: transport,
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
},
|
||||||
|
}
|
||||||
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
|
return &Proxy{adapter, queue.New[C.DelayHistory](10), atomic.NewBool(true)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
|
u, err := url.Parse(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
port := u.Port()
|
||||||
|
if port == "" {
|
||||||
|
switch u.Scheme {
|
||||||
|
case "https":
|
||||||
|
port = "443"
|
||||||
|
case "http":
|
||||||
|
port = "80"
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf("%s scheme not Support", rawURL)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = C.Metadata{
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: u.Hostname(),
|
||||||
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
21
adapter/inbound/http.go
Normal file
21
adapter/inbound/http.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
|
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnContext {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = C.HTTP
|
||||||
|
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
20
adapter/inbound/https.go
Normal file
20
adapter/inbound/https.go
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
|
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
||||||
|
metadata := parseHTTPAddr(request)
|
||||||
|
metadata.Type = C.HTTPCONNECT
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
22
adapter/inbound/mitm.go
Normal file
22
adapter/inbound/mitm.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
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)
|
||||||
|
}
|
33
adapter/inbound/packet.go
Normal file
33
adapter/inbound/packet.go
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
||||||
|
type PacketAdapter struct {
|
||||||
|
C.UDPPacket
|
||||||
|
metadata *C.Metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata returns destination metadata
|
||||||
|
func (s *PacketAdapter) Metadata() *C.Metadata {
|
||||||
|
return s.metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPacket is PacketAdapter generator
|
||||||
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.UDP
|
||||||
|
metadata.Type = source
|
||||||
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return &PacketAdapter{
|
||||||
|
UDPPacket: packet,
|
||||||
|
metadata: metadata,
|
||||||
|
}
|
||||||
|
}
|
22
adapter/inbound/socket.go
Normal file
22
adapter/inbound/socket.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = source
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
@ -1,12 +1,15 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
@ -16,15 +19,14 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
metadata.Host = string(target[2 : 2+target[1]])
|
// trim for FQDN
|
||||||
|
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
||||||
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
case socks5.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
ip := net.IP(target[1 : 1+net.IPv4len])
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
||||||
metadata.DstIP = &ip
|
|
||||||
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:
|
||||||
ip := net.IP(target[1 : 1+net.IPv6len])
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv6len]))
|
||||||
metadata.DstIP = &ip
|
|
||||||
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]))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,35 +40,37 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
port = "80"
|
port = "80"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trim FQDN (#737)
|
||||||
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
Type: C.HTTP,
|
|
||||||
AddrType: C.AtypDomainName,
|
AddrType: C.AtypDomainName,
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: nil,
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if ip != nil {
|
if err == nil {
|
||||||
switch {
|
switch {
|
||||||
case ip.To4() == nil:
|
case ip.Is6():
|
||||||
metadata.AddrType = C.AtypIPv6
|
metadata.AddrType = C.AtypIPv6
|
||||||
default:
|
default:
|
||||||
metadata.AddrType = C.AtypIPv4
|
metadata.AddrType = C.AtypIPv4
|
||||||
}
|
}
|
||||||
metadata.DstIP = &ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr string) (*net.IP, string, error) {
|
func parseAddr(addr string) (netip.Addr, string, error) {
|
||||||
host, port, err := net.SplitHostPort(addr)
|
host, port, err := net.SplitHostPort(addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return netip.Addr{}, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
return &ip, port, nil
|
return ip, port, err
|
||||||
}
|
}
|
138
adapter/outbound/base.go
Normal file
138
adapter/outbound/base.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Base struct {
|
||||||
|
name string
|
||||||
|
addr string
|
||||||
|
iface string
|
||||||
|
tp C.AdapterType
|
||||||
|
udp bool
|
||||||
|
rmark int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name implements C.ProxyAdapter
|
||||||
|
func (b *Base) Name() string {
|
||||||
|
return b.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type implements C.ProxyAdapter
|
||||||
|
func (b *Base) Type() C.AdapterType {
|
||||||
|
return b.tp
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
return c, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (b *Base) SupportUDP() bool {
|
||||||
|
return b.udp
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": b.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Addr implements C.ProxyAdapter
|
||||||
|
func (b *Base) Addr() string {
|
||||||
|
return b.addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialOptions return []dialer.Option from struct
|
||||||
|
func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
||||||
|
if b.iface != "" {
|
||||||
|
opts = append(opts, dialer.WithInterface(b.iface))
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.rmark != 0 {
|
||||||
|
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
||||||
|
}
|
||||||
|
|
||||||
|
return opts
|
||||||
|
}
|
||||||
|
|
||||||
|
type BasicOption struct {
|
||||||
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type BaseOption struct {
|
||||||
|
Name string
|
||||||
|
Addr string
|
||||||
|
Type C.AdapterType
|
||||||
|
UDP bool
|
||||||
|
Interface string
|
||||||
|
RoutingMark int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBase(opt BaseOption) *Base {
|
||||||
|
return &Base{
|
||||||
|
name: opt.Name,
|
||||||
|
addr: opt.Addr,
|
||||||
|
tp: opt.Type,
|
||||||
|
udp: opt.UDP,
|
||||||
|
iface: opt.Interface,
|
||||||
|
rmark: opt.RoutingMark,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type conn struct {
|
||||||
|
net.Conn
|
||||||
|
chain C.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chains implements C.Connection
|
||||||
|
func (c *conn) Chains() C.Chain {
|
||||||
|
return c.chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendToChains implements C.Connection
|
||||||
|
func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
||||||
|
c.chain = append(c.chain, a.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
|
return &conn{c, []string{a.Name()}}
|
||||||
|
}
|
||||||
|
|
||||||
|
type packetConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
chain C.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chains implements C.Connection
|
||||||
|
func (c *packetConn) Chains() C.Chain {
|
||||||
|
return c.chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendToChains implements C.Connection
|
||||||
|
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
||||||
|
c.chain = append(c.chain, a.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
|
return &packetConn{pc, []string{a.Name()}}
|
||||||
|
}
|
48
adapter/outbound/direct.go
Normal file
48
adapter/outbound/direct.go
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Direct struct {
|
||||||
|
*Base
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
opts = append(opts, dialer.WithDirect())
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return NewConn(c, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
opts = append(opts, dialer.WithDirect())
|
||||||
|
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&directPacketConn{pc}, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type directPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDirect() *Direct {
|
||||||
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: "DIRECT",
|
||||||
|
tp: C.Direct,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
149
adapter/outbound/http.go
Normal file
149
adapter/outbound/http.go
Normal file
@ -0,0 +1,149 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Http struct {
|
||||||
|
*Base
|
||||||
|
user string
|
||||||
|
pass string
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type HttpOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
if h.tlsConfig != nil {
|
||||||
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
|
err := cc.Handshake()
|
||||||
|
c = cc
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.shakeHand(metadata, c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", h.addr, h.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = h.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
|
addr := metadata.RemoteAddress()
|
||||||
|
req := &http.Request{
|
||||||
|
Method: http.MethodConnect,
|
||||||
|
URL: &url.URL{
|
||||||
|
Host: addr,
|
||||||
|
},
|
||||||
|
Host: addr,
|
||||||
|
Header: http.Header{
|
||||||
|
"Proxy-Connection": []string{"Keep-Alive"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.user != "" && h.pass != "" {
|
||||||
|
auth := h.user + ":" + h.pass
|
||||||
|
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 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusOK {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusProxyAuthRequired {
|
||||||
|
return errors.New("HTTP need auth")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusMethodNotAllowed {
|
||||||
|
return errors.New("CONNECT method not allowed by proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= http.StatusInternalServerError {
|
||||||
|
return errors.New(resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHttp(option HttpOption) *Http {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
|
sni := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
sni = option.SNI
|
||||||
|
}
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Http{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Http,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
user: option.UserName,
|
||||||
|
pass: option.Password,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
49
adapter/outbound/mitm.go
Normal file
49
adapter/outbound/mitm.go
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
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{}),
|
||||||
|
}
|
||||||
|
}
|
89
adapter/outbound/reject.go
Normal file
89
adapter/outbound/reject.go
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
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 {
|
||||||
|
*Base
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewReject() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "REJECT",
|
||||||
|
tp: C.Reject,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type nopConn struct{}
|
||||||
|
|
||||||
|
func (rw *nopConn) Read(b []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *nopConn) Write(b []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *nopConn) Close() error { return nil }
|
||||||
|
func (rw *nopConn) LocalAddr() net.Addr { return nil }
|
||||||
|
func (rw *nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw *nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (rw *nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw *nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
|
func (npc *nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
||||||
|
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||||
|
func (npc *nopPacketConn) Close() error { return nil }
|
||||||
|
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
|
||||||
|
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
204
adapter/outbound/shadowsocks.go
Normal file
204
adapter/outbound/shadowsocks.go
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ShadowSocks struct {
|
||||||
|
*Base
|
||||||
|
cipher core.Cipher
|
||||||
|
|
||||||
|
// obfs
|
||||||
|
obfsMode string
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
v2rayOption *v2rayObfs.Option
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShadowSocksOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type simpleObfsOption struct {
|
||||||
|
Mode string `obfs:"mode,omitempty"`
|
||||||
|
Host string `obfs:"host,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type v2rayObfsOption struct {
|
||||||
|
Mode string `obfs:"mode"`
|
||||||
|
Host string `obfs:"host,omitempty"`
|
||||||
|
Path string `obfs:"path,omitempty"`
|
||||||
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
switch ss.obfsMode {
|
||||||
|
case "tls":
|
||||||
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
|
case "http":
|
||||||
|
_, port, _ := net.SplitHostPort(ss.addr)
|
||||||
|
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||||
|
case "websocket":
|
||||||
|
var err error
|
||||||
|
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c = ss.cipher.StreamConn(c)
|
||||||
|
_, err := c.Write(serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = ss.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, ss), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
pc.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc = ss.cipher.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
cipher := option.Cipher
|
||||||
|
password := option.Password
|
||||||
|
ciph, err := core.PickCipher(cipher, nil, password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var v2rayOption *v2rayObfs.Option
|
||||||
|
var obfsOption *simpleObfsOption
|
||||||
|
obfsMode := ""
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
|
if option.Plugin == "obfs" {
|
||||||
|
opts := simpleObfsOption{Host: "bing.com"}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "tls" && opts.Mode != "http" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
|
}
|
||||||
|
obfsMode = opts.Mode
|
||||||
|
obfsOption = &opts
|
||||||
|
} else if option.Plugin == "v2ray-plugin" {
|
||||||
|
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "websocket" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
|
}
|
||||||
|
obfsMode = opts.Mode
|
||||||
|
v2rayOption = &v2rayObfs.Option{
|
||||||
|
Host: opts.Host,
|
||||||
|
Path: opts.Path,
|
||||||
|
Headers: opts.Headers,
|
||||||
|
Mux: opts.Mux,
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.TLS {
|
||||||
|
v2rayOption.TLS = true
|
||||||
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ShadowSocks{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Shadowsocks,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
cipher: ciph,
|
||||||
|
|
||||||
|
obfsMode: obfsMode,
|
||||||
|
v2rayOption: v2rayOption,
|
||||||
|
obfsOption: obfsOption,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type ssPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := spc.PacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := socks5.SplitAddr(b[:n])
|
||||||
|
if addr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(b, b[len(addr):])
|
||||||
|
return n - len(addr), udpAddr, e
|
||||||
|
}
|
158
adapter/outbound/shadowsocksr.go
Normal file
158
adapter/outbound/shadowsocksr.go
Normal file
@ -0,0 +1,158 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowstream"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ShadowSocksR struct {
|
||||||
|
*Base
|
||||||
|
cipher core.Cipher
|
||||||
|
obfs obfs.Obfs
|
||||||
|
protocol protocol.Protocol
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShadowSocksROption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
Obfs string `proxy:"obfs"`
|
||||||
|
ObfsParam string `proxy:"obfs-param,omitempty"`
|
||||||
|
Protocol string `proxy:"protocol"`
|
||||||
|
ProtocolParam string `proxy:"protocol-param,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
c = ssr.obfs.StreamConn(c)
|
||||||
|
c = ssr.cipher.StreamConn(c)
|
||||||
|
var (
|
||||||
|
iv []byte
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
switch conn := c.(type) {
|
||||||
|
case *shadowstream.Conn:
|
||||||
|
iv, err = conn.ObtainWriteIV()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case *shadowaead.Conn:
|
||||||
|
return nil, fmt.Errorf("invalid connection type")
|
||||||
|
}
|
||||||
|
c = ssr.protocol.StreamConn(c, iv)
|
||||||
|
_, err = c.Write(serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
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...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, ssr), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ssr.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ssr.addr)
|
||||||
|
if err != nil {
|
||||||
|
pc.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
// SSR protocol compatibility
|
||||||
|
// https://github.com/Dreamacro/clash/pull/2056
|
||||||
|
if option.Cipher == "none" {
|
||||||
|
option.Cipher = "dummy"
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
cipher := option.Cipher
|
||||||
|
password := option.Password
|
||||||
|
coreCiph, err := core.PickCipher(cipher, nil, password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ssr %s initialize error: %w", addr, err)
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
ivSize int
|
||||||
|
key []byte
|
||||||
|
)
|
||||||
|
|
||||||
|
if option.Cipher == "dummy" {
|
||||||
|
ivSize = 0
|
||||||
|
key = core.Kdf(option.Password, 16)
|
||||||
|
} else {
|
||||||
|
ciph, ok := coreCiph.(*core.StreamCipher)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("%s is not none or a supported stream cipher in ssr", cipher)
|
||||||
|
}
|
||||||
|
ivSize = ciph.IVSize()
|
||||||
|
key = ciph.Key
|
||||||
|
}
|
||||||
|
|
||||||
|
obfs, obfsOverhead, err := obfs.PickObfs(option.Obfs, &obfs.Base{
|
||||||
|
Host: option.Server,
|
||||||
|
Port: option.Port,
|
||||||
|
Key: key,
|
||||||
|
IVSize: ivSize,
|
||||||
|
Param: option.ObfsParam,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ssr %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
protocol, err := protocol.PickProtocol(option.Protocol, &protocol.Base{
|
||||||
|
Key: key,
|
||||||
|
Overhead: obfsOverhead,
|
||||||
|
Param: option.ProtocolParam,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ssr %s initialize protocol error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ShadowSocksR{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.ShadowsocksR,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
cipher: coreCiph,
|
||||||
|
obfs: obfs,
|
||||||
|
protocol: protocol,
|
||||||
|
}, nil
|
||||||
|
}
|
164
adapter/outbound/snell.go
Normal file
164
adapter/outbound/snell.go
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/snell"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Snell struct {
|
||||||
|
*Base
|
||||||
|
psk []byte
|
||||||
|
pool *snell.Pool
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
version int
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnellOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Psk string `proxy:"psk"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Version int `proxy:"version,omitempty"`
|
||||||
|
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type streamOption struct {
|
||||||
|
psk []byte
|
||||||
|
version int
|
||||||
|
addr string
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
}
|
||||||
|
|
||||||
|
func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
||||||
|
switch option.obfsOption.Mode {
|
||||||
|
case "tls":
|
||||||
|
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
|
||||||
|
case "http":
|
||||||
|
_, port, _ := net.SplitHostPort(option.addr)
|
||||||
|
c = obfs.NewHTTPObfs(c, option.obfsOption.Host, port)
|
||||||
|
}
|
||||||
|
return snell.StreamConn(c, option.psk, option.version)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
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})
|
||||||
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
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 {
|
||||||
|
c, err := s.pool.Get()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = s.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
psk := []byte(option.Psk)
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
|
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
||||||
|
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
||||||
|
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch obfsOption.Mode {
|
||||||
|
case "tls", "http", "":
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// backward compatible
|
||||||
|
if option.Version == 0 {
|
||||||
|
option.Version = snell.DefaultSnellVersion
|
||||||
|
}
|
||||||
|
switch option.Version {
|
||||||
|
case snell.Version1, snell.Version2:
|
||||||
|
if option.UDP {
|
||||||
|
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
|
||||||
|
}
|
||||||
|
case snell.Version3:
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("snell version error: %d", option.Version)
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Snell{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Snell,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
psk: psk,
|
||||||
|
obfsOption: obfsOption,
|
||||||
|
version: option.Version,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Version == snell.Version2 {
|
||||||
|
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", addr, s.Base.DialOptions()...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
204
adapter/outbound/socks5.go
Normal file
204
adapter/outbound/socks5.go
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Socks5 struct {
|
||||||
|
*Base
|
||||||
|
user string
|
||||||
|
pass string
|
||||||
|
tls bool
|
||||||
|
skipCertVerify bool
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type Socks5Option struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
if ss.tls {
|
||||||
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
|
err := cc.Handshake()
|
||||||
|
c = cc
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var user *socks5.User
|
||||||
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = ss.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
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...)...)
|
||||||
|
if err != nil {
|
||||||
|
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)
|
||||||
|
|
||||||
|
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...)...)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: option.Server,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Socks5{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Socks5,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
user: option.UserName,
|
||||||
|
pass: option.Password,
|
||||||
|
tls: option.TLS,
|
||||||
|
skipCertVerify: option.SkipCertVerify,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type socksPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
tcpConn net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := uc.PacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
addr, payload, err := socks5.DecodeUDPPacket(b)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse udp addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// due to DecodeUDPPacket is mutable, record addr length
|
||||||
|
copy(b, payload)
|
||||||
|
return n - len(addr) - 3, udpAddr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) Close() error {
|
||||||
|
uc.tcpConn.Close()
|
||||||
|
return uc.PacketConn.Close()
|
||||||
|
}
|
238
adapter/outbound/trojan.go
Normal file
238
adapter/outbound/trojan.go
Normal file
@ -0,0 +1,238 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Trojan struct {
|
||||||
|
*Base
|
||||||
|
instance *trojan.Trojan
|
||||||
|
option *TrojanOption
|
||||||
|
|
||||||
|
// for gun mux
|
||||||
|
gunTLSConfig *tls.Config
|
||||||
|
gunConfig *gun.Config
|
||||||
|
transport *http2.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
type TrojanOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Network string `proxy:"network,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
Flow string `proxy:"flow,omitempty"`
|
||||||
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||||
|
if t.option.Network == "ws" {
|
||||||
|
host, port, _ := net.SplitHostPort(t.addr)
|
||||||
|
wsOpts := &trojan.WebsocketOption{
|
||||||
|
Host: host,
|
||||||
|
Port: port,
|
||||||
|
Path: t.option.WSOpts.Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.option.SNI != "" {
|
||||||
|
wsOpts.Host = t.option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(t.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
|
for key, value := range t.option.WSOpts.Headers {
|
||||||
|
header.Add(key, value)
|
||||||
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
|
}
|
||||||
|
|
||||||
|
return t.instance.StreamWebsocketConn(c, wsOpts)
|
||||||
|
}
|
||||||
|
|
||||||
|
return t.instance.StreamConn(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
if t.transport != nil {
|
||||||
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = t.plainStream(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
// gun transport
|
||||||
|
if t.transport != nil && len(opts) == 0 {
|
||||||
|
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = t.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
var c net.Conn
|
||||||
|
|
||||||
|
// grpc transport
|
||||||
|
if t.transport != nil && len(opts) == 0 {
|
||||||
|
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = t.plainStream(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
|
tOption := &trojan.Option{
|
||||||
|
Password: option.Password,
|
||||||
|
ALPN: option.ALPN,
|
||||||
|
ServerName: option.Server,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
FlowShow: option.FlowShow,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
|
option.Flow = option.Flow[:16]
|
||||||
|
switch option.Flow {
|
||||||
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
|
tOption.Flow = option.Flow
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.SNI != "" {
|
||||||
|
tOption.ServerName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
t := &Trojan{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Trojan,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
instance: trojan.New(tOption),
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Network == "grpc" {
|
||||||
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
NextProtos: option.ALPN,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
InsecureSkipVerify: tOption.SkipCertVerify,
|
||||||
|
ServerName: tOption.ServerName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.option.Flow != "" {
|
||||||
|
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
|
} else {
|
||||||
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.gunTLSConfig = tlsConfig
|
||||||
|
t.gunConfig = &gun.Config{
|
||||||
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
|
Host: tOption.ServerName,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
58
adapter/outbound/util.go
Normal file
58
adapter/outbound/util.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
|
var buf [][]byte
|
||||||
|
aType := uint8(metadata.AddrType)
|
||||||
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case socks5.AtypDomainName:
|
||||||
|
lenM := uint8(len(metadata.Host))
|
||||||
|
host := []byte(metadata.Host)
|
||||||
|
buf = [][]byte{{aType, lenM}, host, port}
|
||||||
|
case socks5.AtypIPv4:
|
||||||
|
host := metadata.DstIP.AsSlice()
|
||||||
|
buf = [][]byte{{aType}, host, port}
|
||||||
|
case socks5.AtypIPv6:
|
||||||
|
host := metadata.DstIP.AsSlice()
|
||||||
|
buf = [][]byte{{aType}, host, port}
|
||||||
|
}
|
||||||
|
return bytes.Join(buf, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := resolver.ResolveProxyServerHost(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeConnClose(c net.Conn, err error) {
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Close()
|
||||||
|
}
|
||||||
|
}
|
450
adapter/outbound/vless.go
Normal file
450
adapter/outbound/vless.go
Normal file
@ -0,0 +1,450 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// max packet length
|
||||||
|
maxLength = 1024 << 3
|
||||||
|
)
|
||||||
|
|
||||||
|
type Vless struct {
|
||||||
|
*Base
|
||||||
|
client *vless.Client
|
||||||
|
option *VlessOption
|
||||||
|
|
||||||
|
// for gun mux
|
||||||
|
gunTLSConfig *tls.Config
|
||||||
|
gunConfig *gun.Config
|
||||||
|
transport *http2.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
type VlessOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UUID string `proxy:"uuid"`
|
||||||
|
Flow string `proxy:"flow,omitempty"`
|
||||||
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Network string `proxy:"network,omitempty"`
|
||||||
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
switch v.option.Network {
|
||||||
|
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)
|
||||||
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
|
Host: host,
|
||||||
|
Port: port,
|
||||||
|
Path: v.option.WSOpts.Path,
|
||||||
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
|
header.Add(key, value)
|
||||||
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
|
}
|
||||||
|
|
||||||
|
wsOpts.TLS = true
|
||||||
|
wsOpts.TLSConfig = &tls.Config{
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
ServerName: host,
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
|
case "http":
|
||||||
|
// readability first, so just copy default TLS logic
|
||||||
|
c, err = v.streamTLSOrXTLSConn(c, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
httpOpts := &vmess.HTTPConfig{
|
||||||
|
Host: host,
|
||||||
|
Method: v.option.HTTPOpts.Method,
|
||||||
|
Path: v.option.HTTPOpts.Path,
|
||||||
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
|
}
|
||||||
|
|
||||||
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
|
case "h2":
|
||||||
|
c, err = v.streamTLSOrXTLSConn(c, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
h2Opts := &vmess.H2Config{
|
||||||
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
|
Path: v.option.HTTP2Opts.Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamH2Conn(c, h2Opts)
|
||||||
|
case "grpc":
|
||||||
|
if v.isXTLSEnabled() {
|
||||||
|
c, err = gun.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// default tcp network
|
||||||
|
// handle TLS And XTLS
|
||||||
|
c, err = v.streamTLSOrXTLSConn(c, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
|
if v.isXTLSEnabled() {
|
||||||
|
xtlsOpts := vless.XTLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if isH2 {
|
||||||
|
xtlsOpts.NextProtos = []string{"h2"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
xtlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||||
|
|
||||||
|
} else {
|
||||||
|
tlsOpts := vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if isH2 {
|
||||||
|
tlsOpts.NextProtos = []string{"h2"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vless) isXTLSEnabled() bool {
|
||||||
|
return v.client.Addons != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil && len(opts) == 0 {
|
||||||
|
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, v), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
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
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil && len(opts) == 0 {
|
||||||
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
} else {
|
||||||
|
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.StreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
|
var addrType byte
|
||||||
|
var addr []byte
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case C.AtypIPv4:
|
||||||
|
addrType = byte(vless.AtypIPv4)
|
||||||
|
addr = make([]byte, net.IPv4len)
|
||||||
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
|
case C.AtypIPv6:
|
||||||
|
addrType = byte(vless.AtypIPv6)
|
||||||
|
addr = make([]byte, net.IPv6len)
|
||||||
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
|
case C.AtypDomainName:
|
||||||
|
addrType = byte(vless.AtypDomainName)
|
||||||
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
|
addr[0] = byte(len(metadata.Host))
|
||||||
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
return &vless.DstAddr{
|
||||||
|
UDP: metadata.NetWork == C.UDP,
|
||||||
|
AddrType: addrType,
|
||||||
|
Addr: addr,
|
||||||
|
Port: uint(port),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type vlessPacketConn struct {
|
||||||
|
net.Conn
|
||||||
|
rAddr net.Addr
|
||||||
|
cache [2]byte
|
||||||
|
remain int
|
||||||
|
mux sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
total := len(b)
|
||||||
|
if total == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if total < maxLength {
|
||||||
|
return vc.writePacket(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
offset := 0
|
||||||
|
for {
|
||||||
|
cursor := offset + maxLength
|
||||||
|
if cursor > total {
|
||||||
|
cursor = total
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := vc.writePacket(b[offset:cursor])
|
||||||
|
if err != nil {
|
||||||
|
return offset + n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
offset = cursor
|
||||||
|
if offset == total {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
vc.mux.Lock()
|
||||||
|
defer vc.mux.Unlock()
|
||||||
|
|
||||||
|
if vc.remain != 0 {
|
||||||
|
length := len(b)
|
||||||
|
if length > vc.remain {
|
||||||
|
length = vc.remain
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := vc.Conn.Read(b[:length])
|
||||||
|
if err != nil {
|
||||||
|
return 0, vc.rAddr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
vc.remain -= n
|
||||||
|
|
||||||
|
return n, vc.rAddr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := vc.Conn.Read(b[:2]); err != nil {
|
||||||
|
return 0, vc.rAddr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
total := int(binary.BigEndian.Uint16(b[:2]))
|
||||||
|
if total == 0 {
|
||||||
|
return 0, vc.rAddr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
length := len(b)
|
||||||
|
if length > total {
|
||||||
|
length = total
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(vc.Conn, b[:length]); err != nil {
|
||||||
|
return 0, vc.rAddr, errors.New("read packet error")
|
||||||
|
}
|
||||||
|
|
||||||
|
vc.remain = total - length
|
||||||
|
|
||||||
|
return length, vc.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) {
|
||||||
|
var addons *vless.Addons
|
||||||
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
|
option.Flow = option.Flow[:16]
|
||||||
|
switch option.Flow {
|
||||||
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
|
addons = &vless.Addons{
|
||||||
|
Flow: option.Flow,
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
v := &Vless{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Vless,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
},
|
||||||
|
client: client,
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "h2":
|
||||||
|
if len(option.HTTP2Opts.Host) == 0 {
|
||||||
|
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
||||||
|
}
|
||||||
|
case "grpc":
|
||||||
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
gunConfig := &gun.Config{
|
||||||
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
|
Host: v.option.ServerName,
|
||||||
|
}
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
ServerName: v.option.ServerName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
gunConfig.Host = host
|
||||||
|
}
|
||||||
|
|
||||||
|
v.gunTLSConfig = tlsConfig
|
||||||
|
v.gunConfig = gunConfig
|
||||||
|
if v.isXTLSEnabled() {
|
||||||
|
v.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
|
} else {
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return v, nil
|
||||||
|
}
|
378
adapter/outbound/vmess.go
Normal file
378
adapter/outbound/vmess.go
Normal file
@ -0,0 +1,378 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Vmess struct {
|
||||||
|
*Base
|
||||||
|
client *vmess.Client
|
||||||
|
option *VmessOption
|
||||||
|
|
||||||
|
// for gun mux
|
||||||
|
gunTLSConfig *tls.Config
|
||||||
|
gunConfig *gun.Config
|
||||||
|
transport *http2.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
type VmessOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UUID string `proxy:"uuid"`
|
||||||
|
AlterID int `proxy:"alterId"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Network string `proxy:"network,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
|
||||||
|
// TODO: compatible with VMESS WS older version configurations
|
||||||
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPOptions struct {
|
||||||
|
Method string `proxy:"method,omitempty"`
|
||||||
|
Path []string `proxy:"path,omitempty"`
|
||||||
|
Headers map[string][]string `proxy:"headers,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTP2Options struct {
|
||||||
|
Host []string `proxy:"host,omitempty"`
|
||||||
|
Path string `proxy:"path,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GrpcOptions struct {
|
||||||
|
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type WSOptions struct {
|
||||||
|
Path string `proxy:"path,omitempty"`
|
||||||
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
|
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
||||||
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
switch v.option.Network {
|
||||||
|
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)
|
||||||
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
|
Host: host,
|
||||||
|
Port: port,
|
||||||
|
Path: v.option.WSOpts.Path,
|
||||||
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
|
header.Add(key, value)
|
||||||
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.TLS {
|
||||||
|
wsOpts.TLS = true
|
||||||
|
wsOpts.TLSConfig = &tls.Config{
|
||||||
|
ServerName: host,
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
|
case "http":
|
||||||
|
// readability first, so just copy default TLS logic
|
||||||
|
if v.option.TLS {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsOpts := &vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
httpOpts := &vmess.HTTPConfig{
|
||||||
|
Host: host,
|
||||||
|
Method: v.option.HTTPOpts.Method,
|
||||||
|
Path: v.option.HTTPOpts.Path,
|
||||||
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
|
}
|
||||||
|
|
||||||
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
|
case "h2":
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsOpts := vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
NextProtos: []string{"h2"},
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, &tlsOpts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
h2Opts := &vmess.H2Config{
|
||||||
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
|
Path: v.option.HTTP2Opts.Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamH2Conn(c, h2Opts)
|
||||||
|
case "grpc":
|
||||||
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
default:
|
||||||
|
// handle TLS
|
||||||
|
if v.option.TLS {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsOpts := &vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil && len(opts) == 0 {
|
||||||
|
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, v), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
var c net.Conn
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil && len(opts) == 0 {
|
||||||
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
} else {
|
||||||
|
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.StreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
|
security := strings.ToLower(option.Cipher)
|
||||||
|
client, err := vmess.NewClient(vmess.Config{
|
||||||
|
UUID: option.UUID,
|
||||||
|
AlterID: uint16(option.AlterID),
|
||||||
|
Security: security,
|
||||||
|
HostName: option.Server,
|
||||||
|
Port: strconv.Itoa(option.Port),
|
||||||
|
IsAead: option.AlterID == 0,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "h2", "grpc":
|
||||||
|
if !option.TLS {
|
||||||
|
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
v := &Vmess{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Vmess,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
client: client,
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "h2":
|
||||||
|
if len(option.HTTP2Opts.Host) == 0 {
|
||||||
|
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
||||||
|
}
|
||||||
|
case "grpc":
|
||||||
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
gunConfig := &gun.Config{
|
||||||
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
|
Host: v.option.ServerName,
|
||||||
|
}
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
ServerName: v.option.ServerName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
gunConfig.Host = host
|
||||||
|
}
|
||||||
|
|
||||||
|
v.gunTLSConfig = tlsConfig
|
||||||
|
v.gunConfig = gunConfig
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||||
|
var addrType byte
|
||||||
|
var addr []byte
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case C.AtypIPv4:
|
||||||
|
addrType = byte(vmess.AtypIPv4)
|
||||||
|
addr = make([]byte, net.IPv4len)
|
||||||
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
|
case C.AtypIPv6:
|
||||||
|
addrType = byte(vmess.AtypIPv6)
|
||||||
|
addr = make([]byte, net.IPv6len)
|
||||||
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
|
case C.AtypDomainName:
|
||||||
|
addrType = byte(vmess.AtypDomainName)
|
||||||
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
|
addr[0] = byte(len(metadata.Host))
|
||||||
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
return &vmess.DstAddr{
|
||||||
|
UDP: metadata.NetWork == C.UDP,
|
||||||
|
AddrType: addrType,
|
||||||
|
Addr: addr,
|
||||||
|
Port: uint(port),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type vmessPacketConn struct {
|
||||||
|
net.Conn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
return uc.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, err := uc.Conn.Read(b)
|
||||||
|
return n, uc.rAddr, err
|
||||||
|
}
|
24
adapter/outboundgroup/common.go
Normal file
24
adapter/outboundgroup/common.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
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
|
||||||
|
}
|
106
adapter/outboundgroup/fallback.go
Normal file
106
adapter/outboundgroup/fallback.go
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Fallback struct {
|
||||||
|
*outbound.Base
|
||||||
|
disableUDP bool
|
||||||
|
single *singledo.Single[[]C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Now() string {
|
||||||
|
proxy := f.findAliveProxy(false)
|
||||||
|
return proxy.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
proxy := f.findAliveProxy(true)
|
||||||
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
proxy := f.findAliveProxy(true)
|
||||||
|
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) SupportUDP() bool {
|
||||||
|
if f.disableUDP {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy := f.findAliveProxy(false)
|
||||||
|
return proxy.SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range f.proxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"type": f.Type().String(),
|
||||||
|
"now": f.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
proxy := f.findAliveProxy(true)
|
||||||
|
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 {
|
||||||
|
proxies := f.proxies(touch)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
|
return &Fallback{
|
||||||
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
|
Name: option.Name,
|
||||||
|
Type: C.Fallback,
|
||||||
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
disableUDP: option.DisableUDP,
|
||||||
|
}
|
||||||
|
}
|
184
adapter/outboundgroup/loadbalance.go
Normal file
184
adapter/outboundgroup/loadbalance.go
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
)
|
||||||
|
|
||||||
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
||||||
|
|
||||||
|
type LoadBalance struct {
|
||||||
|
*outbound.Base
|
||||||
|
disableUDP bool
|
||||||
|
single *singledo.Single[[]C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
strategyFn strategyFn
|
||||||
|
}
|
||||||
|
|
||||||
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
|
func parseStrategy(config map[string]any) string {
|
||||||
|
if elm, ok := config["strategy"]; ok {
|
||||||
|
if strategy, ok := elm.(string); ok {
|
||||||
|
return strategy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "consistent-hashing"
|
||||||
|
}
|
||||||
|
|
||||||
|
func getKey(metadata *C.Metadata) string {
|
||||||
|
if metadata.Host != "" {
|
||||||
|
// ip host
|
||||||
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
|
return metadata.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
|
||||||
|
return etld
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !metadata.DstIP.IsValid() {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata.DstIP.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func jumpHash(key uint64, buckets int32) int32 {
|
||||||
|
var b, j int64
|
||||||
|
|
||||||
|
for j < int64(buckets) {
|
||||||
|
b = j
|
||||||
|
key = key*2862933555777941757 + 1
|
||||||
|
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return int32(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
|
||||||
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (pc C.PacketConn, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) SupportUDP() bool {
|
||||||
|
return !lb.disableUDP
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyRoundRobin() strategyFn {
|
||||||
|
idx := 0
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
|
length := len(proxies)
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
idx = (idx + 1) % length
|
||||||
|
proxy := proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyConsistentHashing() strategyFn {
|
||||||
|
maxRetry := 5
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
|
buckets := int32(len(proxies))
|
||||||
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
|
idx := jumpHash(key, buckets)
|
||||||
|
proxy := proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
proxies := lb.proxies(true)
|
||||||
|
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
|
||||||
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range lb.proxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"type": lb.Type().String(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||||
|
var strategyFn strategyFn
|
||||||
|
switch strategy {
|
||||||
|
case "consistent-hashing":
|
||||||
|
strategyFn = strategyConsistentHashing()
|
||||||
|
case "round-robin":
|
||||||
|
strategyFn = strategyRoundRobin()
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
|
}
|
||||||
|
return &LoadBalance{
|
||||||
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
|
Name: option.Name,
|
||||||
|
Type: C.LoadBalance,
|
||||||
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
strategyFn: strategyFn,
|
||||||
|
disableUDP: option.DisableUDP,
|
||||||
|
}, nil
|
||||||
|
}
|
147
adapter/outboundgroup/parser.go
Normal file
147
adapter/outboundgroup/parser.go
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errFormat = errors.New("format error")
|
||||||
|
errType = errors.New("unsupport type")
|
||||||
|
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||||
|
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
||||||
|
errDuplicateProvider = errors.New("duplicate provider name")
|
||||||
|
)
|
||||||
|
|
||||||
|
type GroupCommonOption struct {
|
||||||
|
outbound.BasicOption
|
||||||
|
Name string `group:"name"`
|
||||||
|
Type string `group:"type"`
|
||||||
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
|
Use []string `group:"use,omitempty"`
|
||||||
|
URL string `group:"url,omitempty"`
|
||||||
|
Interval int `group:"interval,omitempty"`
|
||||||
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
groupOption := &GroupCommonOption{
|
||||||
|
Lazy: true,
|
||||||
|
}
|
||||||
|
if err := decoder.Decode(config, groupOption); err != nil {
|
||||||
|
return nil, errFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.Type == "" || groupOption.Name == "" {
|
||||||
|
return nil, errFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
groupName := groupOption.Name
|
||||||
|
|
||||||
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
|
return nil, errMissProxy
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(groupOption.Proxies) != 0 {
|
||||||
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := providersMap[groupName]; ok {
|
||||||
|
return nil, errDuplicateProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// select don't need health check
|
||||||
|
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
} else {
|
||||||
|
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||||
|
return nil, errMissHealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
providers = append(providers, list...)
|
||||||
|
}
|
||||||
|
|
||||||
|
var group C.ProxyAdapter
|
||||||
|
switch groupOption.Type {
|
||||||
|
case "url-test":
|
||||||
|
opts := parseURLTestOption(config)
|
||||||
|
group = NewURLTest(groupOption, providers, opts...)
|
||||||
|
case "select":
|
||||||
|
group = NewSelector(groupOption, providers)
|
||||||
|
case "fallback":
|
||||||
|
group = NewFallback(groupOption, providers)
|
||||||
|
case "load-balance":
|
||||||
|
strategy := parseStrategy(config)
|
||||||
|
return NewLoadBalance(groupOption, providers, strategy)
|
||||||
|
case "relay":
|
||||||
|
group = NewRelay(groupOption, providers)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
return group, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
||||||
|
var ps []C.Proxy
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
||||||
|
var ps []types.ProxyProvider
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.VehicleType() == types.Compatible {
|
||||||
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
114
adapter/outboundgroup/relay.go
Normal file
114
adapter/outboundgroup/relay.go
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Relay struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single[[]C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
var proxies []C.Proxy
|
||||||
|
for _, proxy := range r.proxies(metadata, true) {
|
||||||
|
if proxy.Type() != C.Direct {
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch len(proxies) {
|
||||||
|
case 0:
|
||||||
|
return outbound.NewDirect().DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
|
case 1:
|
||||||
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
first := proxies[0]
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = last.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return outbound.NewConn(c, r), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range r.rawProxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"type": r.Type().String(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := r.single.Do(func() ([]C.Proxy, error) {
|
||||||
|
return getProvidersProxies(r.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
|
||||||
|
proxies := r.rawProxies(touch)
|
||||||
|
|
||||||
|
for n, proxy := range proxies {
|
||||||
|
subproxy := proxy.Unwrap(metadata)
|
||||||
|
for subproxy != nil {
|
||||||
|
proxies[n] = subproxy
|
||||||
|
subproxy = subproxy.Unwrap(metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
|
return &Relay{
|
||||||
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
|
Name: option.Name,
|
||||||
|
Type: C.Relay,
|
||||||
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
114
adapter/outboundgroup/selector.go
Normal file
114
adapter/outboundgroup/selector.go
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Selector struct {
|
||||||
|
*outbound.Base
|
||||||
|
disableUDP bool
|
||||||
|
single *singledo.Single[C.Proxy]
|
||||||
|
selected string
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
c, err := s.selectedProxy(true).DialContext(ctx, metadata, s.Base.DialOptions(opts...)...)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (s *Selector) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
pc, err := s.selectedProxy(true).ListenPacketContext(ctx, metadata, s.Base.DialOptions(opts...)...)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (s *Selector) SupportUDP() bool {
|
||||||
|
if s.disableUDP {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.selectedProxy(false).SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"type": s.Type().String(),
|
||||||
|
"now": s.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Now() string {
|
||||||
|
return s.selectedProxy(false).Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Set(name string) error {
|
||||||
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
s.selected = name
|
||||||
|
s.single.Reset()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.New("proxy not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
return s.selectedProxy(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
|
elm, _, _ := s.single.Do(func() (C.Proxy, error) {
|
||||||
|
proxies := getProvidersProxies(s.providers, touch)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Name() == s.selected {
|
||||||
|
return proxy, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0], nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
||||||
|
selected := providers[0].Proxies()[0].Name()
|
||||||
|
return &Selector{
|
||||||
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
|
Name: option.Name,
|
||||||
|
Type: C.Selector,
|
||||||
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
}),
|
||||||
|
single: singledo.NewSingle[C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
selected: selected,
|
||||||
|
disableUDP: option.DisableUDP,
|
||||||
|
}
|
||||||
|
}
|
156
adapter/outboundgroup/urltest.go
Normal file
156
adapter/outboundgroup/urltest.go
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type urlTestOption func(*URLTest)
|
||||||
|
|
||||||
|
func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
||||||
|
return func(u *URLTest) {
|
||||||
|
u.tolerance = tolerance
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type URLTest struct {
|
||||||
|
*outbound.Base
|
||||||
|
tolerance uint16
|
||||||
|
disableUDP bool
|
||||||
|
fastNode C.Proxy
|
||||||
|
single *singledo.Single[[]C.Proxy]
|
||||||
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Now() string {
|
||||||
|
return u.fast(false).Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
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 {
|
||||||
|
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
|
proxies := u.proxies(touch)
|
||||||
|
fast := proxies[0]
|
||||||
|
min := fast.LastDelay()
|
||||||
|
fastNotExist := true
|
||||||
|
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
if u.fastNode != nil && proxy.Name() == u.fastNode.Name() {
|
||||||
|
fastNotExist = false
|
||||||
|
}
|
||||||
|
|
||||||
|
if !proxy.Alive() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delay := proxy.LastDelay()
|
||||||
|
if delay < min {
|
||||||
|
fast = proxy
|
||||||
|
min = delay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tolerance
|
||||||
|
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||||
|
u.fastNode = fast
|
||||||
|
}
|
||||||
|
|
||||||
|
return u.fastNode, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) SupportUDP() bool {
|
||||||
|
if u.disableUDP {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return u.fast(false).SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range u.proxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"type": u.Type().String(),
|
||||||
|
"now": u.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
|
// tolerance
|
||||||
|
if elm, ok := config["tolerance"]; ok {
|
||||||
|
if tolerance, ok := elm.(int); ok {
|
||||||
|
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return opts
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
|
urlTest := &URLTest{
|
||||||
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
|
Name: option.Name,
|
||||||
|
Type: C.URLTest,
|
||||||
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
|
providers: providers,
|
||||||
|
disableUDP: option.DisableUDP,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(urlTest)
|
||||||
|
}
|
||||||
|
|
||||||
|
return urlTest
|
||||||
|
}
|
52
adapter/outboundgroup/util.go
Normal file
52
adapter/outboundgroup/util.go
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
||||||
|
host, port, err := net.SplitHostPort(rawAddress)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("addrToMetadata failed: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err != nil {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: host,
|
||||||
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else if ip.Is4() {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv4,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv6,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
93
adapter/parser.go
Normal file
93
adapter/parser.go
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
package adapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
|
proxyType, existType := mapping["type"].(string)
|
||||||
|
if !existType {
|
||||||
|
return nil, fmt.Errorf("missing type")
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
proxy C.ProxyAdapter
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
switch proxyType {
|
||||||
|
case "ss":
|
||||||
|
ssOption := &outbound.ShadowSocksOption{}
|
||||||
|
err = decoder.Decode(mapping, ssOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewShadowSocks(*ssOption)
|
||||||
|
case "ssr":
|
||||||
|
ssrOption := &outbound.ShadowSocksROption{}
|
||||||
|
err = decoder.Decode(mapping, ssrOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewShadowSocksR(*ssrOption)
|
||||||
|
case "socks5":
|
||||||
|
socksOption := &outbound.Socks5Option{}
|
||||||
|
err = decoder.Decode(mapping, socksOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewSocks5(*socksOption)
|
||||||
|
case "http":
|
||||||
|
httpOption := &outbound.HttpOption{}
|
||||||
|
err = decoder.Decode(mapping, httpOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewHttp(*httpOption)
|
||||||
|
case "vmess":
|
||||||
|
vmessOption := &outbound.VmessOption{
|
||||||
|
HTTPOpts: outbound.HTTPOptions{
|
||||||
|
Method: "GET",
|
||||||
|
Path: []string{"/"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
|
case "vless":
|
||||||
|
vlessOption := &outbound.VlessOption{}
|
||||||
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewVless(*vlessOption)
|
||||||
|
case "snell":
|
||||||
|
snellOption := &outbound.SnellOption{}
|
||||||
|
err = decoder.Decode(mapping, snellOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
|
case "trojan":
|
||||||
|
trojanOption := &outbound.TrojanOption{}
|
||||||
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewProxy(proxy), nil
|
||||||
|
}
|
185
adapter/provider/fetcher.go
Normal file
185
adapter/provider/fetcher.go
Normal file
@ -0,0 +1,185 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
fileMode os.FileMode = 0o666
|
||||||
|
dirMode os.FileMode = 0o755
|
||||||
|
)
|
||||||
|
|
||||||
|
type parser = func([]byte) (any, error)
|
||||||
|
|
||||||
|
type fetcher struct {
|
||||||
|
name string
|
||||||
|
vehicle types.Vehicle
|
||||||
|
updatedAt *time.Time
|
||||||
|
ticker *time.Ticker
|
||||||
|
done chan struct{}
|
||||||
|
hash [16]byte
|
||||||
|
parser parser
|
||||||
|
onUpdate func(any)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Name() string {
|
||||||
|
return f.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) VehicleType() types.VehicleType {
|
||||||
|
return f.vehicle.Type()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Initial() (any, error) {
|
||||||
|
var (
|
||||||
|
buf []byte
|
||||||
|
err error
|
||||||
|
isLocal bool
|
||||||
|
)
|
||||||
|
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
||||||
|
buf, err = os.ReadFile(f.vehicle.Path())
|
||||||
|
modTime := stat.ModTime()
|
||||||
|
f.updatedAt = &modTime
|
||||||
|
isLocal = true
|
||||||
|
} else {
|
||||||
|
buf, err = f.vehicle.Read()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
if !isLocal {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse local file error, fallback to remote
|
||||||
|
buf, err = f.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err = f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
isLocal = false
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.vehicle.Type() != types.File && !isLocal {
|
||||||
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.hash = md5.Sum(buf)
|
||||||
|
|
||||||
|
// pull proxies automatically
|
||||||
|
if f.ticker != nil {
|
||||||
|
go f.pullLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Update() (any, bool, error) {
|
||||||
|
buf, err := f.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
hash := md5.Sum(buf)
|
||||||
|
if bytes.Equal(f.hash[:], hash[:]) {
|
||||||
|
f.updatedAt = &now
|
||||||
|
os.Chtimes(f.vehicle.Path(), now, now)
|
||||||
|
return nil, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.vehicle.Type() != types.File {
|
||||||
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.updatedAt = &now
|
||||||
|
f.hash = hash
|
||||||
|
|
||||||
|
return proxies, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Destroy() error {
|
||||||
|
if f.ticker != nil {
|
||||||
|
f.done <- struct{}{}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) pullLoop() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-f.ticker.C:
|
||||||
|
elm, same, err := f.Update()
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if same {
|
||||||
|
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Infoln("[Provider] %s's proxies update", f.Name())
|
||||||
|
if f.onUpdate != nil {
|
||||||
|
f.onUpdate(elm)
|
||||||
|
}
|
||||||
|
case <-f.done:
|
||||||
|
f.ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeWrite(path string, buf []byte) error {
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
if err := os.MkdirAll(dir, dirMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return os.WriteFile(path, buf, fileMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
|
||||||
|
var ticker *time.Ticker
|
||||||
|
if interval != 0 {
|
||||||
|
ticker = time.NewTicker(interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &fetcher{
|
||||||
|
name: name,
|
||||||
|
ticker: ticker,
|
||||||
|
vehicle: vehicle,
|
||||||
|
parser: parser,
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
onUpdate: onUpdate,
|
||||||
|
}
|
||||||
|
}
|
94
adapter/provider/healthcheck.go
Normal file
94
adapter/provider/healthcheck.go
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultURLTestTimeout = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
type HealthCheckOption struct {
|
||||||
|
URL string
|
||||||
|
Interval uint
|
||||||
|
}
|
||||||
|
|
||||||
|
type HealthCheck struct {
|
||||||
|
url string
|
||||||
|
proxies []C.Proxy
|
||||||
|
interval uint
|
||||||
|
lazy bool
|
||||||
|
lastTouch *atomic.Int64
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) process() {
|
||||||
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
t := time.NewTicker(30 * time.Second)
|
||||||
|
<-t.C
|
||||||
|
t.Stop()
|
||||||
|
hc.check()
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
}
|
||||||
|
case <-hc.done:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
|
hc.proxies = proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) auto() bool {
|
||||||
|
return hc.interval != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) touch() {
|
||||||
|
hc.lastTouch.Store(time.Now().Unix())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) check() {
|
||||||
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
|
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.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) close() {
|
||||||
|
hc.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *HealthCheck {
|
||||||
|
return &HealthCheck{
|
||||||
|
proxies: proxies,
|
||||||
|
url: url,
|
||||||
|
interval: interval,
|
||||||
|
lazy: lazy,
|
||||||
|
lastTouch: atomic.NewInt64(0),
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
}
|
64
adapter/provider/parser.go
Normal file
64
adapter/provider/parser.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
var errVehicleType = errors.New("unsupport vehicle type")
|
||||||
|
|
||||||
|
type healthCheckSchema struct {
|
||||||
|
Enable bool `provider:"enable"`
|
||||||
|
URL string `provider:"url"`
|
||||||
|
Interval int `provider:"interval"`
|
||||||
|
Lazy bool `provider:"lazy,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxyProviderSchema struct {
|
||||||
|
Type string `provider:"type"`
|
||||||
|
Path string `provider:"path"`
|
||||||
|
URL string `provider:"url,omitempty"`
|
||||||
|
Interval int `provider:"interval,omitempty"`
|
||||||
|
Filter string `provider:"filter,omitempty"`
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
schema := &proxyProviderSchema{
|
||||||
|
HealthCheck: healthCheckSchema{
|
||||||
|
Lazy: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var hcInterval uint
|
||||||
|
if schema.HealthCheck.Enable {
|
||||||
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
|
}
|
||||||
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
|
||||||
|
|
||||||
|
path := C.Path.Resolve(schema.Path)
|
||||||
|
|
||||||
|
var vehicle types.Vehicle
|
||||||
|
switch schema.Type {
|
||||||
|
case "file":
|
||||||
|
vehicle = NewFileVehicle(path)
|
||||||
|
case "http":
|
||||||
|
vehicle = NewHTTPVehicle(schema.URL, path)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
|
filter := schema.Filter
|
||||||
|
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
||||||
|
}
|
235
adapter/provider/provider.go
Normal file
235
adapter/provider/provider.go
Normal file
@ -0,0 +1,235 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ReservedName = "default"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProxySchema struct {
|
||||||
|
Proxies []map[string]any `yaml:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// for auto gc
|
||||||
|
type ProxySetProvider struct {
|
||||||
|
*proxySetProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxySetProvider struct {
|
||||||
|
*fetcher
|
||||||
|
proxies []C.Proxy
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"name": pp.Name(),
|
||||||
|
"type": pp.Type().String(),
|
||||||
|
"vehicleType": pp.VehicleType().String(),
|
||||||
|
"proxies": pp.Proxies(),
|
||||||
|
"updatedAt": pp.updatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Name() string {
|
||||||
|
return pp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) HealthCheck() {
|
||||||
|
pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Update() error {
|
||||||
|
elm, same, err := pp.fetcher.Update()
|
||||||
|
if err == nil && !same {
|
||||||
|
pp.onUpdate(elm)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Initial() error {
|
||||||
|
elm, err := pp.fetcher.Initial()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pp.onUpdate(elm)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Type() types.ProviderType {
|
||||||
|
return types.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Proxies() []C.Proxy {
|
||||||
|
return pp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
|
pp.healthCheck.touch()
|
||||||
|
return pp.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
|
pp.proxies = proxies
|
||||||
|
pp.healthCheck.setProxy(proxies)
|
||||||
|
if pp.healthCheck.auto() {
|
||||||
|
go pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
|
pd.healthCheck.close()
|
||||||
|
pd.fetcher.Destroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
|
filterReg, err := regexp.Compile(filter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
pd := &proxySetProvider{
|
||||||
|
proxies: []C.Proxy{},
|
||||||
|
healthCheck: hc,
|
||||||
|
}
|
||||||
|
|
||||||
|
onUpdate := func(elm any) {
|
||||||
|
ret := elm.([]C.Proxy)
|
||||||
|
pd.setProxies(ret)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesParseAndFilter := func(buf []byte) (any, error) {
|
||||||
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if schema.Proxies == nil {
|
||||||
|
return nil, errors.New("file must have a `proxies` field")
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for idx, mapping := range schema.Proxies {
|
||||||
|
if name, ok := mapping["name"]; ok && len(filter) > 0 && !filterReg.MatchString(name.(string)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
if len(filter) > 0 {
|
||||||
|
return nil, errors.New("doesn't match any proxy, please check your filter")
|
||||||
|
}
|
||||||
|
return nil, errors.New("file doesn't have any proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fetcher := newFetcher(name, interval, vehicle, proxiesParseAndFilter, onUpdate)
|
||||||
|
pd.fetcher = fetcher
|
||||||
|
|
||||||
|
wrapper := &ProxySetProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
|
return wrapper, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// for auto gc
|
||||||
|
type CompatibleProvider struct {
|
||||||
|
*compatibleProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type compatibleProvider struct {
|
||||||
|
name string
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
proxies []C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"name": cp.Name(),
|
||||||
|
"type": cp.Type().String(),
|
||||||
|
"vehicleType": cp.VehicleType().String(),
|
||||||
|
"proxies": cp.Proxies(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Name() string {
|
||||||
|
return cp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) HealthCheck() {
|
||||||
|
cp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Update() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Initial() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) VehicleType() types.VehicleType {
|
||||||
|
return types.Compatible
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Type() types.ProviderType {
|
||||||
|
return types.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Proxies() []C.Proxy {
|
||||||
|
return cp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
|
cp.healthCheck.touch()
|
||||||
|
return cp.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
|
pd.healthCheck.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("provider need one proxy at least")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
pd := &compatibleProvider{
|
||||||
|
name: name,
|
||||||
|
proxies: proxies,
|
||||||
|
healthCheck: hc,
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &CompatibleProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||||
|
return wrapper, nil
|
||||||
|
}
|
98
adapter/provider/vehicle.go
Normal file
98
adapter/provider/vehicle.go
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FileVehicle struct {
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Type() types.VehicleType {
|
||||||
|
return types.File
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Path() string {
|
||||||
|
return f.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Read() ([]byte, error) {
|
||||||
|
return os.ReadFile(f.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFileVehicle(path string) *FileVehicle {
|
||||||
|
return &FileVehicle{path: path}
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPVehicle struct {
|
||||||
|
url string
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Type() types.VehicleType {
|
||||||
|
return types.HTTP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Path() string {
|
||||||
|
return h.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
uri, err := url.Parse(h.url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if user := uri.User; user != nil {
|
||||||
|
password, _ := user.Password()
|
||||||
|
req.SetBasicAuth(user.Username(), password)
|
||||||
|
}
|
||||||
|
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{Transport: transport}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
buf, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
||||||
|
return &HTTPVehicle{url, path}
|
||||||
|
}
|
@ -1,59 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// HTTPAdapter is a adapter for HTTP connection
|
|
||||||
type HTTPAdapter struct {
|
|
||||||
net.Conn
|
|
||||||
metadata *C.Metadata
|
|
||||||
R *http.Request
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata return destination metadata
|
|
||||||
func (h *HTTPAdapter) Metadata() *C.Metadata {
|
|
||||||
return h.metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewHTTP is HTTPAdapter generator
|
|
||||||
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
|
||||||
metadata := parseHTTPAddr(request)
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
return &HTTPAdapter{
|
|
||||||
metadata: metadata,
|
|
||||||
R: request,
|
|
||||||
Conn: conn,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoveHopByHopHeaders remove hop-by-hop header
|
|
||||||
func RemoveHopByHopHeaders(header http.Header) {
|
|
||||||
// Strip hop-by-hop header based on RFC:
|
|
||||||
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
|
|
||||||
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
|
|
||||||
|
|
||||||
header.Del("Proxy-Connection")
|
|
||||||
header.Del("Proxy-Authenticate")
|
|
||||||
header.Del("Proxy-Authorization")
|
|
||||||
header.Del("TE")
|
|
||||||
header.Del("Trailers")
|
|
||||||
header.Del("Transfer-Encoding")
|
|
||||||
header.Del("Upgrade")
|
|
||||||
|
|
||||||
connections := header.Get("Connection")
|
|
||||||
header.Del("Connection")
|
|
||||||
if len(connections) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, h := range strings.Split(connections, ",") {
|
|
||||||
header.Del(strings.TrimSpace(h))
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,19 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewHTTPS is HTTPAdapter generator
|
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
|
||||||
metadata := parseHTTPAddr(request)
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
return &SocketAdapter{
|
|
||||||
metadata: metadata,
|
|
||||||
Conn: conn,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SocketAdapter is a adapter for socks and redir connection
|
|
||||||
type SocketAdapter struct {
|
|
||||||
net.Conn
|
|
||||||
metadata *C.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata return destination metadata
|
|
||||||
func (s *SocketAdapter) Metadata() *C.Metadata {
|
|
||||||
return s.metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSocket is SocketAdapter generator
|
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, netType C.NetWork) *SocketAdapter {
|
|
||||||
metadata := parseSocksAddr(target)
|
|
||||||
metadata.NetWork = netType
|
|
||||||
metadata.Type = source
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
|
|
||||||
return &SocketAdapter{
|
|
||||||
Conn: conn,
|
|
||||||
metadata: metadata,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,148 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Base struct {
|
|
||||||
name string
|
|
||||||
tp C.AdapterType
|
|
||||||
udp bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) Name() string {
|
|
||||||
return b.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) Type() C.AdapterType {
|
|
||||||
return b.tp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
return nil, nil, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) SupportUDP() bool {
|
|
||||||
return b.udp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) Destroy() {}
|
|
||||||
|
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]string{
|
|
||||||
"type": b.Type().String(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
type Proxy struct {
|
|
||||||
C.ProxyAdapter
|
|
||||||
history *queue.Queue
|
|
||||||
alive bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Proxy) Alive() bool {
|
|
||||||
return p.alive
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Proxy) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
conn, err := p.ProxyAdapter.Dial(metadata)
|
|
||||||
if err != nil {
|
|
||||||
p.alive = false
|
|
||||||
}
|
|
||||||
return conn, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Proxy) DelayHistory() []C.DelayHistory {
|
|
||||||
queue := p.history.Copy()
|
|
||||||
histories := []C.DelayHistory{}
|
|
||||||
for _, item := range queue {
|
|
||||||
histories = append(histories, item.(C.DelayHistory))
|
|
||||||
}
|
|
||||||
return histories
|
|
||||||
}
|
|
||||||
|
|
||||||
// LastDelay return last history record. if proxy is not alive, return the max value of int16.
|
|
||||||
func (p *Proxy) LastDelay() (delay uint16) {
|
|
||||||
var max uint16 = 0xffff
|
|
||||||
if !p.alive {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
|
|
||||||
head := p.history.First()
|
|
||||||
if head == nil {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
history := head.(C.DelayHistory)
|
|
||||||
if history.Delay == 0 {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
return history.Delay
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|
||||||
inner, err := p.ProxyAdapter.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
return inner, err
|
|
||||||
}
|
|
||||||
|
|
||||||
mapping := map[string]interface{}{}
|
|
||||||
json.Unmarshal(inner, &mapping)
|
|
||||||
mapping["history"] = p.DelayHistory()
|
|
||||||
return json.Marshal(mapping)
|
|
||||||
}
|
|
||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
|
||||||
func (p *Proxy) URLTest(url string) (t uint16, err error) {
|
|
||||||
defer func() {
|
|
||||||
p.alive = err == nil
|
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
|
||||||
if err == nil {
|
|
||||||
record.Delay = t
|
|
||||||
}
|
|
||||||
p.history.Put(record)
|
|
||||||
if p.history.Len() > 10 {
|
|
||||||
p.history.Pop()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
addr, err := urlToMetadata(url)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
|
||||||
instance, err := p.Dial(&addr)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer instance.Close()
|
|
||||||
transport := &http.Transport{
|
|
||||||
Dial: func(string, string) (net.Conn, error) {
|
|
||||||
return instance, nil
|
|
||||||
},
|
|
||||||
// from http.DefaultTransport
|
|
||||||
MaxIdleConns: 100,
|
|
||||||
IdleConnTimeout: 90 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
}
|
|
||||||
client := http.Client{Transport: transport}
|
|
||||||
resp, err := client.Get(url)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resp.Body.Close()
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
|
||||||
return &Proxy{adapter, queue.New(10), true}
|
|
||||||
}
|
|
@ -1,48 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Direct struct {
|
|
||||||
*Base
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Direct) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
address := net.JoinHostPort(metadata.Host, metadata.DstPort)
|
|
||||||
if metadata.DstIP != nil {
|
|
||||||
address = net.JoinHostPort(metadata.DstIP.String(), metadata.DstPort)
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err := net.DialTimeout("tcp", address, tcpTimeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Direct) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
pc, err := net.ListenPacket("udp", "")
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(metadata.String(), metadata.DstPort))
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
return pc, addr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "DIRECT",
|
|
||||||
tp: C.Direct,
|
|
||||||
udp: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,125 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Fallback struct {
|
|
||||||
*Base
|
|
||||||
proxies []C.Proxy
|
|
||||||
rawURL string
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type FallbackOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.Dial(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.DialUDP(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) SupportUDP() bool {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range f.proxies {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": f.Type().String(),
|
|
||||||
"now": f.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Destroy() {
|
|
||||||
f.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) loop() {
|
|
||||||
tick := time.NewTicker(f.interval)
|
|
||||||
go f.validTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go f.validTest()
|
|
||||||
case <-f.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy() C.Proxy {
|
|
||||||
for _, proxy := range f.proxies {
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return f.proxies[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) validTest() {
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(f.proxies))
|
|
||||||
|
|
||||||
for _, p := range f.proxies {
|
|
||||||
go func(p C.Proxy) {
|
|
||||||
p.URLTest(f.rawURL)
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
|
||||||
_, err := urlToMetadata(option.URL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) < 1 {
|
|
||||||
return nil, errors.New("The number of proxies cannot be 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
|
|
||||||
Fallback := &Fallback{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Fallback,
|
|
||||||
},
|
|
||||||
proxies: proxies,
|
|
||||||
rawURL: option.URL,
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
|
||||||
go Fallback.loop()
|
|
||||||
return Fallback, nil
|
|
||||||
}
|
|
@ -1,120 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"bytes"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/base64"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Http struct {
|
|
||||||
*Base
|
|
||||||
addr string
|
|
||||||
user string
|
|
||||||
pass string
|
|
||||||
tls bool
|
|
||||||
skipCertVerify bool
|
|
||||||
tlsConfig *tls.Config
|
|
||||||
}
|
|
||||||
|
|
||||||
type HttpOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
UserName string `proxy:"username,omitempty"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
c, err := net.DialTimeout("tcp", h.addr, tcpTimeout)
|
|
||||||
if err == nil && h.tls {
|
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
|
||||||
err = cc.Handshake()
|
|
||||||
c = cc
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", h.addr)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
if err := h.shakeHand(metadata, c); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
var err error
|
|
||||||
|
|
||||||
addr := net.JoinHostPort(metadata.String(), metadata.DstPort)
|
|
||||||
buf.WriteString("CONNECT " + addr + " HTTP/1.1\r\n")
|
|
||||||
buf.WriteString("Host: " + metadata.String() + "\r\n")
|
|
||||||
buf.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
|
||||||
auth := h.user + ":" + h.pass
|
|
||||||
buf.WriteString("Proxy-Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) + "\r\n")
|
|
||||||
}
|
|
||||||
// header ended
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
|
|
||||||
_, err = rw.Write(buf.Bytes())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
var req http.Request
|
|
||||||
resp, err := http.ReadResponse(bufio.NewReader(rw), &req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode == 200 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode == 407 {
|
|
||||||
return errors.New("HTTP need auth")
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode == 405 {
|
|
||||||
return errors.New("CONNECT method not allowed by proxy")
|
|
||||||
}
|
|
||||||
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHttp(option HttpOption) *Http {
|
|
||||||
var tlsConfig *tls.Config
|
|
||||||
if option.TLS {
|
|
||||||
tlsConfig = &tls.Config{
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
ClientSessionCache: getClientSessionCache(),
|
|
||||||
ServerName: option.Server,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Http{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Http,
|
|
||||||
},
|
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
user: option.UserName,
|
|
||||||
pass: option.Password,
|
|
||||||
tls: option.TLS,
|
|
||||||
skipCertVerify: option.SkipCertVerify,
|
|
||||||
tlsConfig: tlsConfig,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,158 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LoadBalance struct {
|
|
||||||
*Base
|
|
||||||
proxies []C.Proxy
|
|
||||||
maxRetry int
|
|
||||||
rawURL string
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getKey(metadata *C.Metadata) string {
|
|
||||||
if metadata.Host != "" {
|
|
||||||
// ip host
|
|
||||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
|
||||||
return metadata.Host
|
|
||||||
}
|
|
||||||
|
|
||||||
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
|
|
||||||
return etld
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if metadata.DstIP == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return metadata.DstIP.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func jumpHash(key uint64, buckets int32) int32 {
|
|
||||||
var b, j int64
|
|
||||||
|
|
||||||
for j < int64(buckets) {
|
|
||||||
b = j
|
|
||||||
key = key*2862933555777941757 + 1
|
|
||||||
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
|
|
||||||
}
|
|
||||||
|
|
||||||
return int32(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
|
||||||
buckets := int32(len(lb.proxies))
|
|
||||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
|
||||||
idx := jumpHash(key, buckets)
|
|
||||||
proxy := lb.proxies[idx]
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy.Dial(metadata)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return lb.proxies[0].Dial(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
|
||||||
buckets := int32(len(lb.proxies))
|
|
||||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
|
||||||
idx := jumpHash(key, buckets)
|
|
||||||
proxy := lb.proxies[idx]
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy.DialUDP(metadata)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return lb.proxies[0].DialUDP(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) SupportUDP() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) Destroy() {
|
|
||||||
lb.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) validTest() {
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(lb.proxies))
|
|
||||||
|
|
||||||
for _, p := range lb.proxies {
|
|
||||||
go func(p C.Proxy) {
|
|
||||||
p.URLTest(lb.rawURL)
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) loop() {
|
|
||||||
tick := time.NewTicker(lb.interval)
|
|
||||||
go lb.validTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go lb.validTest()
|
|
||||||
case <-lb.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range lb.proxies {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": lb.Type().String(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
type LoadBalanceOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLoadBalance(option LoadBalanceOption, proxies []C.Proxy) (*LoadBalance, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("Provide at least one proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
|
|
||||||
lb := &LoadBalance{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.LoadBalance,
|
|
||||||
},
|
|
||||||
proxies: proxies,
|
|
||||||
maxRetry: 3,
|
|
||||||
rawURL: option.URL,
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
|
||||||
go lb.loop()
|
|
||||||
return lb, nil
|
|
||||||
}
|
|
@ -1,54 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Reject struct {
|
|
||||||
*Base
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Reject) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
return &NopConn{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewReject() *Reject {
|
|
||||||
return &Reject{
|
|
||||||
Base: &Base{
|
|
||||||
name: "REJECT",
|
|
||||||
tp: C.Reject,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type NopConn struct{}
|
|
||||||
|
|
||||||
func (rw *NopConn) Read(b []byte) (int, error) {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw *NopConn) Write(b []byte) (int, error) {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is fake function for net.Conn
|
|
||||||
func (rw *NopConn) Close() error { return nil }
|
|
||||||
|
|
||||||
// LocalAddr is fake function for net.Conn
|
|
||||||
func (rw *NopConn) LocalAddr() net.Addr { return nil }
|
|
||||||
|
|
||||||
// RemoteAddr is fake function for net.Conn
|
|
||||||
func (rw *NopConn) RemoteAddr() net.Addr { return nil }
|
|
||||||
|
|
||||||
// SetDeadline is fake function for net.Conn
|
|
||||||
func (rw *NopConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
|
|
||||||
// SetReadDeadline is fake function for net.Conn
|
|
||||||
func (rw *NopConn) SetReadDeadline(time.Time) error { return nil }
|
|
||||||
|
|
||||||
// SetWriteDeadline is fake function for net.Conn
|
|
||||||
func (rw *NopConn) SetWriteDeadline(time.Time) error { return nil }
|
|
@ -1,80 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"sort"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Selector struct {
|
|
||||||
*Base
|
|
||||||
selected C.Proxy
|
|
||||||
proxies map[string]C.Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
type SelectorOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
return s.selected.Dial(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
return s.selected.DialUDP(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) SupportUDP() bool {
|
|
||||||
return s.selected.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for k := range s.proxies {
|
|
||||||
all = append(all, k)
|
|
||||||
}
|
|
||||||
sort.Strings(all)
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": s.Type().String(),
|
|
||||||
"now": s.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Now() string {
|
|
||||||
return s.selected.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
|
||||||
proxy, exist := s.proxies[name]
|
|
||||||
if !exist {
|
|
||||||
return errors.New("Proxy does not exist")
|
|
||||||
}
|
|
||||||
s.selected = proxy
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("Provide at least one proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
mapping := make(map[string]C.Proxy)
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
mapping[proxy.Name()] = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &Selector{
|
|
||||||
Base: &Base{
|
|
||||||
name: name,
|
|
||||||
tp: C.Selector,
|
|
||||||
},
|
|
||||||
proxies: mapping,
|
|
||||||
selected: proxies[0],
|
|
||||||
}
|
|
||||||
return s, nil
|
|
||||||
}
|
|
@ -1,198 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
|
||||||
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
v2rayObfs "github.com/Dreamacro/clash/component/v2ray-plugin"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ShadowSocks struct {
|
|
||||||
*Base
|
|
||||||
server string
|
|
||||||
cipher core.Cipher
|
|
||||||
|
|
||||||
// obfs
|
|
||||||
obfsMode string
|
|
||||||
obfsOption *simpleObfsOption
|
|
||||||
wsOption *v2rayObfs.WebsocketOption
|
|
||||||
}
|
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Password string `proxy:"password"`
|
|
||||||
Cipher string `proxy:"cipher"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
|
||||||
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
|
||||||
|
|
||||||
// deprecated when bump to 1.0
|
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
|
||||||
ObfsHost string `proxy:"obfs-host,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
|
||||||
Mode string `obfs:"mode"`
|
|
||||||
Host string `obfs:"host,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type v2rayObfsOption struct {
|
|
||||||
Mode string `obfs:"mode"`
|
|
||||||
Host string `obfs:"host,omitempty"`
|
|
||||||
Path string `obfs:"path,omitempty"`
|
|
||||||
TLS bool `obfs:"tls,omitempty"`
|
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", ss.server, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
switch ss.obfsMode {
|
|
||||||
case "tls":
|
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
|
||||||
case "http":
|
|
||||||
_, port, _ := net.SplitHostPort(ss.server)
|
|
||||||
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
|
||||||
case "websocket":
|
|
||||||
var err error
|
|
||||||
c, err = v2rayObfs.NewWebsocketObfs(c, ss.wsOption)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", ss.server, err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c = ss.cipher.StreamConn(c)
|
|
||||||
_, err = c.Write(serializesSocksAddr(metadata))
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
pc, err := net.ListenPacket("udp", "")
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := net.ResolveUDPAddr("udp", ss.server)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
remoteAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(metadata.String(), metadata.DstPort))
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc = ss.cipher.PacketConn(pc)
|
|
||||||
return &ssUDPConn{PacketConn: pc, rAddr: remoteAddr}, addr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]string{
|
|
||||||
"type": ss.Type().String(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|
||||||
server := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
cipher := option.Cipher
|
|
||||||
password := option.Password
|
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
var wsOption *v2rayObfs.WebsocketOption
|
|
||||||
var obfsOption *simpleObfsOption
|
|
||||||
obfsMode := ""
|
|
||||||
|
|
||||||
// forward compatibility before 1.0
|
|
||||||
if option.Obfs != "" {
|
|
||||||
obfsMode = option.Obfs
|
|
||||||
obfsOption = &simpleObfsOption{
|
|
||||||
Host: "bing.com",
|
|
||||||
}
|
|
||||||
if option.ObfsHost != "" {
|
|
||||||
obfsOption.Host = option.ObfsHost
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
|
||||||
if option.Plugin == "obfs" {
|
|
||||||
opts := simpleObfsOption{Host: "bing.com"}
|
|
||||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize obfs error: %s", server, err.Error())
|
|
||||||
}
|
|
||||||
obfsMode = opts.Mode
|
|
||||||
obfsOption = &opts
|
|
||||||
} else if option.Plugin == "v2ray-plugin" {
|
|
||||||
opts := v2rayObfsOption{Host: "bing.com"}
|
|
||||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %s", server, err.Error())
|
|
||||||
}
|
|
||||||
obfsMode = opts.Mode
|
|
||||||
var tlsConfig *tls.Config
|
|
||||||
if opts.TLS {
|
|
||||||
tlsConfig = &tls.Config{
|
|
||||||
ServerName: opts.Host,
|
|
||||||
InsecureSkipVerify: opts.SkipCertVerify,
|
|
||||||
ClientSessionCache: getClientSessionCache(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
wsOption = &v2rayObfs.WebsocketOption{
|
|
||||||
Host: opts.Host,
|
|
||||||
Path: opts.Path,
|
|
||||||
Headers: opts.Headers,
|
|
||||||
TLSConfig: tlsConfig,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &ShadowSocks{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Shadowsocks,
|
|
||||||
udp: option.UDP,
|
|
||||||
},
|
|
||||||
server: server,
|
|
||||||
cipher: ciph,
|
|
||||||
|
|
||||||
obfsMode: obfsMode,
|
|
||||||
wsOption: wsOption,
|
|
||||||
obfsOption: obfsOption,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ssUDPConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (uc *ssUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
buf := pool.BufPool.Get().([]byte)
|
|
||||||
defer pool.BufPool.Put(buf[:cap(buf)])
|
|
||||||
rAddr := socks5.ParseAddr(uc.rAddr.String())
|
|
||||||
copy(buf[len(rAddr):], b)
|
|
||||||
copy(buf, rAddr)
|
|
||||||
return uc.PacketConn.WriteTo(buf[:len(rAddr)+len(b)], addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (uc *ssUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
n, a, e := uc.PacketConn.ReadFrom(b)
|
|
||||||
addr := socks5.SplitAddr(b[:n])
|
|
||||||
copy(b, b[len(addr):])
|
|
||||||
return n - len(addr), a, e
|
|
||||||
}
|
|
@ -1,110 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Socks5 struct {
|
|
||||||
*Base
|
|
||||||
addr string
|
|
||||||
user string
|
|
||||||
pass string
|
|
||||||
tls bool
|
|
||||||
skipCertVerify bool
|
|
||||||
tlsConfig *tls.Config
|
|
||||||
}
|
|
||||||
|
|
||||||
type Socks5Option struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
UserName string `proxy:"username,omitempty"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
c, err := net.DialTimeout("tcp", ss.addr, tcpTimeout)
|
|
||||||
|
|
||||||
if err == nil && ss.tls {
|
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
|
||||||
err = cc.Handshake()
|
|
||||||
c = cc
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", ss.addr)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
var user *socks5.User
|
|
||||||
if ss.user != "" {
|
|
||||||
user = &socks5.User{
|
|
||||||
Username: ss.user,
|
|
||||||
Password: ss.pass,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
c, err := net.DialTimeout("tcp", ss.addr, tcpTimeout)
|
|
||||||
|
|
||||||
if err == nil && ss.tls {
|
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
|
||||||
err = cc.Handshake()
|
|
||||||
c = cc
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("%s connect error", ss.addr)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
var user *socks5.User
|
|
||||||
if ss.user != "" {
|
|
||||||
user = &socks5.User{
|
|
||||||
Username: ss.user,
|
|
||||||
Password: ss.pass,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user); err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
return &fakeUDPConn{Conn: c}, c.LocalAddr(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
|
||||||
var tlsConfig *tls.Config
|
|
||||||
if option.TLS {
|
|
||||||
tlsConfig = &tls.Config{
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
ClientSessionCache: getClientSessionCache(),
|
|
||||||
ServerName: option.Server,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Socks5{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Socks5,
|
|
||||||
udp: option.UDP,
|
|
||||||
},
|
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
user: option.UserName,
|
|
||||||
pass: option.Password,
|
|
||||||
tls: option.TLS,
|
|
||||||
skipCertVerify: option.SkipCertVerify,
|
|
||||||
tlsConfig: tlsConfig,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,164 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"sort"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/picker"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type URLTest struct {
|
|
||||||
*Base
|
|
||||||
proxies []C.Proxy
|
|
||||||
rawURL string
|
|
||||||
fast C.Proxy
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
once int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type URLTestOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
|
||||||
return u.fast.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
a, err := u.fast.Dial(metadata)
|
|
||||||
if err != nil {
|
|
||||||
u.fallback()
|
|
||||||
}
|
|
||||||
return a, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
return u.fast.DialUDP(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) SupportUDP() bool {
|
|
||||||
return u.fast.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range u.proxies {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
sort.Strings(all)
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": u.Type().String(),
|
|
||||||
"now": u.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Destroy() {
|
|
||||||
u.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) loop() {
|
|
||||||
tick := time.NewTicker(u.interval)
|
|
||||||
go u.speedTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go u.speedTest()
|
|
||||||
case <-u.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) fallback() {
|
|
||||||
fast := u.proxies[0]
|
|
||||||
min := fast.LastDelay()
|
|
||||||
for _, proxy := range u.proxies[1:] {
|
|
||||||
if !proxy.Alive() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
delay := proxy.LastDelay()
|
|
||||||
if delay < min {
|
|
||||||
fast = proxy
|
|
||||||
min = delay
|
|
||||||
}
|
|
||||||
}
|
|
||||||
u.fast = fast
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) speedTest() {
|
|
||||||
if !atomic.CompareAndSwapInt32(&u.once, 0, 1) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer atomic.StoreInt32(&u.once, 0)
|
|
||||||
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(u.proxies))
|
|
||||||
c := make(chan interface{})
|
|
||||||
fast := picker.SelectFast(context.Background(), c)
|
|
||||||
timer := time.NewTimer(u.interval)
|
|
||||||
|
|
||||||
for _, p := range u.proxies {
|
|
||||||
go func(p C.Proxy) {
|
|
||||||
_, err := p.URLTest(u.rawURL)
|
|
||||||
if err == nil {
|
|
||||||
c <- p
|
|
||||||
}
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
wg.Wait()
|
|
||||||
close(c)
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-timer.C:
|
|
||||||
// Wait for fast to return or close.
|
|
||||||
<-fast
|
|
||||||
case p, open := <-fast:
|
|
||||||
if open {
|
|
||||||
u.fast = p.(C.Proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
|
||||||
_, err := urlToMetadata(option.URL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(proxies) < 1 {
|
|
||||||
return nil, errors.New("The number of proxies cannot be 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
urlTest := &URLTest{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.URLTest,
|
|
||||||
},
|
|
||||||
proxies: proxies[:],
|
|
||||||
rawURL: option.URL,
|
|
||||||
fast: proxies[0],
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
once: 0,
|
|
||||||
}
|
|
||||||
go urlTest.loop()
|
|
||||||
return urlTest, nil
|
|
||||||
}
|
|
@ -1,98 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/tls"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
tcpTimeout = 5 * time.Second
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
globalClientSessionCache tls.ClientSessionCache
|
|
||||||
once sync.Once
|
|
||||||
)
|
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|
||||||
u, err := url.Parse(rawURL)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
port := u.Port()
|
|
||||||
if port == "" {
|
|
||||||
if u.Scheme == "https" {
|
|
||||||
port = "443"
|
|
||||||
} else if u.Scheme == "http" {
|
|
||||||
port = "80"
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("%s scheme not Support", rawURL)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
addr = C.Metadata{
|
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: u.Hostname(),
|
|
||||||
DstIP: nil,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
|
||||||
tcp.SetKeepAlive(true)
|
|
||||||
tcp.SetKeepAlivePeriod(30 * time.Second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getClientSessionCache() tls.ClientSessionCache {
|
|
||||||
once.Do(func() {
|
|
||||||
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
|
||||||
})
|
|
||||||
return globalClientSessionCache
|
|
||||||
}
|
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
|
||||||
var buf [][]byte
|
|
||||||
aType := uint8(metadata.AddrType)
|
|
||||||
p, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
|
||||||
switch metadata.AddrType {
|
|
||||||
case socks5.AtypDomainName:
|
|
||||||
len := uint8(len(metadata.Host))
|
|
||||||
host := []byte(metadata.Host)
|
|
||||||
buf = [][]byte{{aType, len}, host, port}
|
|
||||||
case socks5.AtypIPv4:
|
|
||||||
host := metadata.DstIP.To4()
|
|
||||||
buf = [][]byte{{aType}, host, port}
|
|
||||||
case socks5.AtypIPv6:
|
|
||||||
host := metadata.DstIP.To16()
|
|
||||||
buf = [][]byte{{aType}, host, port}
|
|
||||||
}
|
|
||||||
return bytes.Join(buf, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeUDPConn struct {
|
|
||||||
net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fuc *fakeUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
return fuc.Conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fuc *fakeUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
n, err := fuc.Conn.Read(b)
|
|
||||||
return n, fuc.RemoteAddr(), err
|
|
||||||
}
|
|
@ -1,110 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/vmess"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Vmess struct {
|
|
||||||
*Base
|
|
||||||
server string
|
|
||||||
client *vmess.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
type VmessOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
UUID string `proxy:"uuid"`
|
|
||||||
AlterID int `proxy:"alterId"`
|
|
||||||
Cipher string `proxy:"cipher"`
|
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
Network string `proxy:"network,omitempty"`
|
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) Dial(metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
c, err := net.DialTimeout("tcp", v.server, tcpTimeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", v.server)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = v.client.New(c, parseVmessAddr(metadata))
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
|
||||||
c, err := net.DialTimeout("tcp", v.server, tcpTimeout)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("%s connect error", v.server)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = v.client.New(c, parseVmessAddr(metadata))
|
|
||||||
return &fakeUDPConn{Conn: c}, c.LocalAddr(), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
|
||||||
security := strings.ToLower(option.Cipher)
|
|
||||||
client, err := vmess.NewClient(vmess.Config{
|
|
||||||
UUID: option.UUID,
|
|
||||||
AlterID: uint16(option.AlterID),
|
|
||||||
Security: security,
|
|
||||||
TLS: option.TLS,
|
|
||||||
HostName: option.Server,
|
|
||||||
Port: strconv.Itoa(option.Port),
|
|
||||||
NetWork: option.Network,
|
|
||||||
WebSocketPath: option.WSPath,
|
|
||||||
WebSocketHeaders: option.WSHeaders,
|
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
|
||||||
SessionCacahe: getClientSessionCache(),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Vmess{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Vmess,
|
|
||||||
udp: option.UDP,
|
|
||||||
},
|
|
||||||
server: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
client: client,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
|
||||||
var addrType byte
|
|
||||||
var addr []byte
|
|
||||||
switch metadata.AddrType {
|
|
||||||
case C.AtypIPv4:
|
|
||||||
addrType = byte(vmess.AtypIPv4)
|
|
||||||
addr = make([]byte, net.IPv4len)
|
|
||||||
copy(addr[:], metadata.DstIP.To4())
|
|
||||||
case C.AtypIPv6:
|
|
||||||
addrType = byte(vmess.AtypIPv6)
|
|
||||||
addr = make([]byte, net.IPv6len)
|
|
||||||
copy(addr[:], metadata.DstIP.To16())
|
|
||||||
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.Atoi(metadata.DstPort)
|
|
||||||
return &vmess.DstAddr{
|
|
||||||
UDP: metadata.NetWork == C.UDP,
|
|
||||||
AddrType: addrType,
|
|
||||||
Addr: addr,
|
|
||||||
Port: uint(port),
|
|
||||||
}
|
|
||||||
}
|
|
105
common/batch/batch.go
Normal file
105
common/batch/batch.go
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
package batch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Option[T any] func(b *Batch[T])
|
||||||
|
|
||||||
|
type Result[T any] struct {
|
||||||
|
Value T
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Error struct {
|
||||||
|
Key string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithConcurrencyNum[T any](n int) Option[T] {
|
||||||
|
return func(b *Batch[T]) {
|
||||||
|
q := make(chan struct{}, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
q <- struct{}{}
|
||||||
|
}
|
||||||
|
b.queue = q
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Batch similar to errgroup, but can control the maximum number of concurrent
|
||||||
|
type Batch[T any] struct {
|
||||||
|
result map[string]Result[T]
|
||||||
|
queue chan struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
mux sync.Mutex
|
||||||
|
err *Error
|
||||||
|
once sync.Once
|
||||||
|
cancel func()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch[T]) Go(key string, fn func() (T, error)) {
|
||||||
|
b.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer b.wg.Done()
|
||||||
|
if b.queue != nil {
|
||||||
|
<-b.queue
|
||||||
|
defer func() {
|
||||||
|
b.queue <- struct{}{}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
value, err := fn()
|
||||||
|
if err != nil {
|
||||||
|
b.once.Do(func() {
|
||||||
|
b.err = &Error{key, err}
|
||||||
|
if b.cancel != nil {
|
||||||
|
b.cancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
ret := Result[T]{value, err}
|
||||||
|
b.mux.Lock()
|
||||||
|
defer b.mux.Unlock()
|
||||||
|
b.result[key] = ret
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch[T]) Wait() *Error {
|
||||||
|
b.wg.Wait()
|
||||||
|
if b.cancel != nil {
|
||||||
|
b.cancel()
|
||||||
|
}
|
||||||
|
return b.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch[T]) WaitAndGetResult() (map[string]Result[T], *Error) {
|
||||||
|
err := b.Wait()
|
||||||
|
return b.Result(), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch[T]) Result() map[string]Result[T] {
|
||||||
|
b.mux.Lock()
|
||||||
|
defer b.mux.Unlock()
|
||||||
|
copyM := map[string]Result[T]{}
|
||||||
|
for k, v := range b.result {
|
||||||
|
copyM[k] = v
|
||||||
|
}
|
||||||
|
return copyM
|
||||||
|
}
|
||||||
|
|
||||||
|
func New[T any](ctx context.Context, opts ...Option[T]) (*Batch[T], context.Context) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
|
||||||
|
b := &Batch[T]{
|
||||||
|
result: map[string]Result[T]{},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range opts {
|
||||||
|
o(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
b.cancel = cancel
|
||||||
|
return b, ctx
|
||||||
|
}
|
83
common/batch/batch_test.go
Normal file
83
common/batch/batch_test.go
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
package batch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBatch(t *testing.T) {
|
||||||
|
b, _ := New[string](context.Background())
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
b.Go("foo", func() (string, error) {
|
||||||
|
time.Sleep(time.Millisecond * 100)
|
||||||
|
return "foo", nil
|
||||||
|
})
|
||||||
|
b.Go("bar", func() (string, error) {
|
||||||
|
time.Sleep(time.Millisecond * 150)
|
||||||
|
return "bar", nil
|
||||||
|
})
|
||||||
|
result, err := b.WaitAndGetResult()
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
duration := time.Since(now)
|
||||||
|
assert.Less(t, duration, time.Millisecond*200)
|
||||||
|
assert.Equal(t, 2, len(result))
|
||||||
|
|
||||||
|
for k, v := range result {
|
||||||
|
assert.NoError(t, v.Err)
|
||||||
|
assert.Equal(t, k, v.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBatchWithConcurrencyNum(t *testing.T) {
|
||||||
|
b, _ := New[string](
|
||||||
|
context.Background(),
|
||||||
|
WithConcurrencyNum[string](3),
|
||||||
|
)
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
for i := 0; i < 7; i++ {
|
||||||
|
idx := i
|
||||||
|
b.Go(strconv.Itoa(idx), func() (string, error) {
|
||||||
|
time.Sleep(time.Millisecond * 100)
|
||||||
|
return strconv.Itoa(idx), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
result, _ := b.WaitAndGetResult()
|
||||||
|
duration := time.Since(now)
|
||||||
|
assert.Greater(t, duration, time.Millisecond*260)
|
||||||
|
assert.Equal(t, 7, len(result))
|
||||||
|
|
||||||
|
for k, v := range result {
|
||||||
|
assert.NoError(t, v.Err)
|
||||||
|
assert.Equal(t, k, v.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBatchContext(t *testing.T) {
|
||||||
|
b, ctx := New[string](context.Background())
|
||||||
|
|
||||||
|
b.Go("error", func() (string, error) {
|
||||||
|
time.Sleep(time.Millisecond * 100)
|
||||||
|
return "", errors.New("test error")
|
||||||
|
})
|
||||||
|
|
||||||
|
b.Go("ctx", func() (string, error) {
|
||||||
|
<-ctx.Done()
|
||||||
|
return "", ctx.Err()
|
||||||
|
})
|
||||||
|
|
||||||
|
result, err := b.WaitAndGetResult()
|
||||||
|
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
assert.Equal(t, "error", err.Key)
|
||||||
|
|
||||||
|
assert.Equal(t, ctx.Err(), result["ctx"].Err)
|
||||||
|
}
|
50
common/cache/cache.go
vendored
50
common/cache/cache.go
vendored
@ -7,50 +7,50 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Cache store element with a expired time
|
// Cache store element with a expired time
|
||||||
type Cache struct {
|
type Cache[K comparable, V any] struct {
|
||||||
*cache
|
*cache[K, V]
|
||||||
}
|
}
|
||||||
|
|
||||||
type cache struct {
|
type cache[K comparable, V any] struct {
|
||||||
mapping sync.Map
|
mapping sync.Map
|
||||||
janitor *janitor
|
janitor *janitor[K, V]
|
||||||
}
|
}
|
||||||
|
|
||||||
type element struct {
|
type element[V any] struct {
|
||||||
Expired time.Time
|
Expired time.Time
|
||||||
Payload interface{}
|
Payload V
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put element in Cache with its ttl
|
// Put element in Cache with its ttl
|
||||||
func (c *cache) Put(key interface{}, payload interface{}, ttl time.Duration) {
|
func (c *cache[K, V]) Put(key K, payload V, ttl time.Duration) {
|
||||||
c.mapping.Store(key, &element{
|
c.mapping.Store(key, &element[V]{
|
||||||
Payload: payload,
|
Payload: payload,
|
||||||
Expired: time.Now().Add(ttl),
|
Expired: time.Now().Add(ttl),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get element in Cache, and drop when it expired
|
// Get element in Cache, and drop when it expired
|
||||||
func (c *cache) Get(key interface{}) interface{} {
|
func (c *cache[K, V]) Get(key K) V {
|
||||||
item, exist := c.mapping.Load(key)
|
item, exist := c.mapping.Load(key)
|
||||||
if !exist {
|
if !exist {
|
||||||
return nil
|
return getZero[V]()
|
||||||
}
|
}
|
||||||
elm := item.(*element)
|
elm := item.(*element[V])
|
||||||
// expired
|
// expired
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
c.mapping.Delete(key)
|
c.mapping.Delete(key)
|
||||||
return nil
|
return getZero[V]()
|
||||||
}
|
}
|
||||||
return elm.Payload
|
return elm.Payload
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire element in Cache with Expire Time
|
// GetWithExpire element in Cache with Expire Time
|
||||||
func (c *cache) GetWithExpire(key interface{}) (payload interface{}, expired time.Time) {
|
func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
||||||
item, exist := c.mapping.Load(key)
|
item, exist := c.mapping.Load(key)
|
||||||
if !exist {
|
if !exist {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
elm := item.(*element)
|
elm := item.(*element[V])
|
||||||
// expired
|
// expired
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
c.mapping.Delete(key)
|
c.mapping.Delete(key)
|
||||||
@ -59,10 +59,10 @@ func (c *cache) GetWithExpire(key interface{}) (payload interface{}, expired tim
|
|||||||
return elm.Payload, elm.Expired
|
return elm.Payload, elm.Expired
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *cache) cleanup() {
|
func (c *cache[K, V]) cleanup() {
|
||||||
c.mapping.Range(func(k, v interface{}) bool {
|
c.mapping.Range(func(k, v any) bool {
|
||||||
key := k.(string)
|
key := k.(string)
|
||||||
elm := v.(*element)
|
elm := v.(*element[V])
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
c.mapping.Delete(key)
|
c.mapping.Delete(key)
|
||||||
}
|
}
|
||||||
@ -70,12 +70,12 @@ func (c *cache) cleanup() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
type janitor struct {
|
type janitor[K comparable, V any] struct {
|
||||||
interval time.Duration
|
interval time.Duration
|
||||||
stop chan struct{}
|
stop chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *janitor) process(c *cache) {
|
func (j *janitor[K, V]) process(c *cache[K, V]) {
|
||||||
ticker := time.NewTicker(j.interval)
|
ticker := time.NewTicker(j.interval)
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@ -88,19 +88,19 @@ func (j *janitor) process(c *cache) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopJanitor(c *Cache) {
|
func stopJanitor[K comparable, V any](c *Cache[K, V]) {
|
||||||
c.janitor.stop <- struct{}{}
|
c.janitor.stop <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// New return *Cache
|
// New return *Cache
|
||||||
func New(interval time.Duration) *Cache {
|
func New[K comparable, V any](interval time.Duration) *Cache[K, V] {
|
||||||
j := &janitor{
|
j := &janitor[K, V]{
|
||||||
interval: interval,
|
interval: interval,
|
||||||
stop: make(chan struct{}),
|
stop: make(chan struct{}),
|
||||||
}
|
}
|
||||||
c := &cache{janitor: j}
|
c := &cache[K, V]{janitor: j}
|
||||||
go j.process(c)
|
go j.process(c)
|
||||||
C := &Cache{c}
|
C := &Cache[K, V]{c}
|
||||||
runtime.SetFinalizer(C, stopJanitor)
|
runtime.SetFinalizer(C, stopJanitor[K, V])
|
||||||
return C
|
return C
|
||||||
}
|
}
|
||||||
|
44
common/cache/cache_test.go
vendored
44
common/cache/cache_test.go
vendored
@ -4,55 +4,57 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCache_Basic(t *testing.T) {
|
func TestCache_Basic(t *testing.T) {
|
||||||
interval := 200 * time.Millisecond
|
interval := 200 * time.Millisecond
|
||||||
ttl := 20 * time.Millisecond
|
ttl := 20 * time.Millisecond
|
||||||
c := New(interval)
|
c := New[string, int](interval)
|
||||||
c.Put("int", 1, ttl)
|
c.Put("int", 1, ttl)
|
||||||
c.Put("string", "a", ttl)
|
|
||||||
|
d := New[string, string](interval)
|
||||||
|
d.Put("string", "a", ttl)
|
||||||
|
|
||||||
i := c.Get("int")
|
i := c.Get("int")
|
||||||
if i.(int) != 1 {
|
assert.Equal(t, i, 1, "should recv 1")
|
||||||
t.Error("should recv 1")
|
|
||||||
}
|
|
||||||
|
|
||||||
s := c.Get("string")
|
s := d.Get("string")
|
||||||
if s.(string) != "a" {
|
assert.Equal(t, s, "a", "should recv 'a'")
|
||||||
t.Error("should recv 'a'")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCache_TTL(t *testing.T) {
|
func TestCache_TTL(t *testing.T) {
|
||||||
interval := 200 * time.Millisecond
|
interval := 200 * time.Millisecond
|
||||||
ttl := 20 * time.Millisecond
|
ttl := 20 * time.Millisecond
|
||||||
c := New(interval)
|
now := time.Now()
|
||||||
|
c := New[string, int](interval)
|
||||||
c.Put("int", 1, ttl)
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("int2", 2, ttl)
|
||||||
|
|
||||||
i := c.Get("int")
|
i := c.Get("int")
|
||||||
if i.(int) != 1 {
|
_, expired := c.GetWithExpire("int2")
|
||||||
t.Error("should recv 1")
|
assert.Equal(t, i, 1, "should recv 1")
|
||||||
}
|
assert.True(t, now.Before(expired))
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
time.Sleep(ttl * 2)
|
||||||
i = c.Get("int")
|
i = c.Get("int")
|
||||||
if i != nil {
|
j, _ := c.GetWithExpire("int2")
|
||||||
t.Error("should recv nil")
|
assert.True(t, i == 0, "should recv 0")
|
||||||
}
|
assert.True(t, j == 0, "should recv 0")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCache_AutoCleanup(t *testing.T) {
|
func TestCache_AutoCleanup(t *testing.T) {
|
||||||
interval := 10 * time.Millisecond
|
interval := 10 * time.Millisecond
|
||||||
ttl := 15 * time.Millisecond
|
ttl := 15 * time.Millisecond
|
||||||
c := New(interval)
|
c := New[string, int](interval)
|
||||||
c.Put("int", 1, ttl)
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
time.Sleep(ttl * 2)
|
||||||
i := c.Get("int")
|
i := c.Get("int")
|
||||||
if i != nil {
|
j, _ := c.GetWithExpire("int")
|
||||||
t.Error("should recv nil")
|
assert.True(t, i == 0, "should recv 0")
|
||||||
}
|
assert.True(t, j == 0, "should recv 0")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCache_AutoGC(t *testing.T) {
|
func TestCache_AutoGC(t *testing.T) {
|
||||||
@ -60,7 +62,7 @@ func TestCache_AutoGC(t *testing.T) {
|
|||||||
go func() {
|
go func() {
|
||||||
interval := 10 * time.Millisecond
|
interval := 10 * time.Millisecond
|
||||||
ttl := 15 * time.Millisecond
|
ttl := 15 * time.Millisecond
|
||||||
c := New(interval)
|
c := New[string, int](interval)
|
||||||
c.Put("int", 1, ttl)
|
c.Put("int", 1, ttl)
|
||||||
sign <- struct{}{}
|
sign <- struct{}{}
|
||||||
}()
|
}()
|
||||||
|
238
common/cache/lrucache.go
vendored
Normal file
238
common/cache/lrucache.go
vendored
Normal file
@ -0,0 +1,238 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
// Modified by https://github.com/die-net/lrucache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/generics/list"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Option is part of Functional Options Pattern
|
||||||
|
type Option[K comparable, V any] func(*LruCache[K, V])
|
||||||
|
|
||||||
|
// EvictCallback is used to get a callback when a cache entry is evicted
|
||||||
|
type EvictCallback[K comparable, V any] func(key K, value V)
|
||||||
|
|
||||||
|
// WithEvict set the evict callback
|
||||||
|
func WithEvict[K comparable, V any](cb EvictCallback[K, V]) Option[K, V] {
|
||||||
|
return func(l *LruCache[K, V]) {
|
||||||
|
l.onEvict = cb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithUpdateAgeOnGet update expires when Get element
|
||||||
|
func WithUpdateAgeOnGet[K comparable, V any]() Option[K, V] {
|
||||||
|
return func(l *LruCache[K, V]) {
|
||||||
|
l.updateAgeOnGet = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithAge defined element max age (second)
|
||||||
|
func WithAge[K comparable, V any](maxAge int64) Option[K, V] {
|
||||||
|
return func(l *LruCache[K, V]) {
|
||||||
|
l.maxAge = maxAge
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithSize defined max length of LruCache
|
||||||
|
func WithSize[K comparable, V any](maxSize int) Option[K, V] {
|
||||||
|
return func(l *LruCache[K, V]) {
|
||||||
|
l.maxSize = maxSize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithStale decide whether Stale return is enabled.
|
||||||
|
// If this feature is enabled, element will not get Evicted according to `WithAge`.
|
||||||
|
func WithStale[K comparable, V any](stale bool) Option[K, V] {
|
||||||
|
return func(l *LruCache[K, V]) {
|
||||||
|
l.staleReturn = stale
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LruCache is a thread-safe, in-memory lru-cache that evicts the
|
||||||
|
// least recently used entries from memory when (if set) the entries are
|
||||||
|
// older than maxAge (in seconds). Use the New constructor to create one.
|
||||||
|
type LruCache[K comparable, V any] struct {
|
||||||
|
maxAge int64
|
||||||
|
maxSize int
|
||||||
|
mu sync.Mutex
|
||||||
|
cache map[K]*list.Element[*entry[K, V]]
|
||||||
|
lru *list.List[*entry[K, V]] // Front is least-recent
|
||||||
|
updateAgeOnGet bool
|
||||||
|
staleReturn bool
|
||||||
|
onEvict EvictCallback[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLRUCache creates an LruCache
|
||||||
|
func NewLRUCache[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
||||||
|
lc := &LruCache[K, V]{
|
||||||
|
lru: list.New[*entry[K, V]](),
|
||||||
|
cache: make(map[K]*list.Element[*entry[K, V]]),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(lc)
|
||||||
|
}
|
||||||
|
|
||||||
|
return lc
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns the any representation of a cached response and a bool
|
||||||
|
// set to true if the key was found.
|
||||||
|
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||||
|
el := c.get(key)
|
||||||
|
if el == nil {
|
||||||
|
return getZero[V](), false
|
||||||
|
}
|
||||||
|
value := el.value
|
||||||
|
|
||||||
|
return value, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWithExpire returns the any representation of a cached response,
|
||||||
|
// a time.Time Give expected expires,
|
||||||
|
// and a bool set to true if the key was found.
|
||||||
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
|
func (c *LruCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
||||||
|
el := c.get(key)
|
||||||
|
if el == nil {
|
||||||
|
return getZero[V](), time.Time{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return el.value, time.Unix(el.expires, 0), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exist returns if key exist in cache but not put item to the head of linked list
|
||||||
|
func (c *LruCache[K, V]) Exist(key K) bool {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
_, ok := c.cache[key]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set stores the any representation of a response for a given key.
|
||||||
|
func (c *LruCache[K, V]) Set(key K, value V) {
|
||||||
|
expires := int64(0)
|
||||||
|
if c.maxAge > 0 {
|
||||||
|
expires = time.Now().Unix() + c.maxAge
|
||||||
|
}
|
||||||
|
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
||||||
|
// The expires time will round to second.
|
||||||
|
func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
if le, ok := c.cache[key]; ok {
|
||||||
|
c.lru.MoveToBack(le)
|
||||||
|
e := le.Value
|
||||||
|
e.value = value
|
||||||
|
e.expires = expires.Unix()
|
||||||
|
} else {
|
||||||
|
e := &entry[K, V]{key: key, value: value, expires: expires.Unix()}
|
||||||
|
c.cache[key] = c.lru.PushBack(e)
|
||||||
|
|
||||||
|
if c.maxSize > 0 {
|
||||||
|
if elLen := c.lru.Len(); elLen > c.maxSize {
|
||||||
|
c.deleteElement(c.lru.Front())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.maybeDeleteOldest()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloneTo clone and overwrite elements to another LruCache
|
||||||
|
func (c *LruCache[K, V]) CloneTo(n *LruCache[K, V]) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
n.mu.Lock()
|
||||||
|
defer n.mu.Unlock()
|
||||||
|
|
||||||
|
n.lru = list.New[*entry[K, V]]()
|
||||||
|
n.cache = make(map[K]*list.Element[*entry[K, V]])
|
||||||
|
|
||||||
|
for e := c.lru.Front(); e != nil; e = e.Next() {
|
||||||
|
elm := e.Value
|
||||||
|
n.cache[elm.key] = n.lru.PushBack(elm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache[K, V]) get(key K) *entry[K, V] {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
le, ok := c.cache[key]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if !c.staleReturn && c.maxAge > 0 && le.Value.expires <= time.Now().Unix() {
|
||||||
|
c.deleteElement(le)
|
||||||
|
c.maybeDeleteOldest()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c.lru.MoveToBack(le)
|
||||||
|
el := le.Value
|
||||||
|
if c.maxAge > 0 && c.updateAgeOnGet {
|
||||||
|
el.expires = time.Now().Unix() + c.maxAge
|
||||||
|
}
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes the value associated with a key.
|
||||||
|
func (c *LruCache[K, V]) Delete(key K) {
|
||||||
|
c.mu.Lock()
|
||||||
|
|
||||||
|
if le, ok := c.cache[key]; ok {
|
||||||
|
c.deleteElement(le)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache[K, V]) maybeDeleteOldest() {
|
||||||
|
if !c.staleReturn && c.maxAge > 0 {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
for le := c.lru.Front(); le != nil && le.Value.expires <= now; le = c.lru.Front() {
|
||||||
|
c.deleteElement(le)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache[K, V]) deleteElement(le *list.Element[*entry[K, V]]) {
|
||||||
|
c.lru.Remove(le)
|
||||||
|
e := le.Value
|
||||||
|
delete(c.cache, e.key)
|
||||||
|
if c.onEvict != nil {
|
||||||
|
c.onEvict(e.key, e.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache[K, V]) Clear() error {
|
||||||
|
c.mu.Lock()
|
||||||
|
|
||||||
|
c.cache = make(map[K]*list.Element[*entry[K, V]])
|
||||||
|
|
||||||
|
c.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type entry[K comparable, V any] struct {
|
||||||
|
key K
|
||||||
|
value V
|
||||||
|
expires int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func getZero[T any]() T {
|
||||||
|
var result T
|
||||||
|
return result
|
||||||
|
}
|
184
common/cache/lrucache_test.go
vendored
Normal file
184
common/cache/lrucache_test.go
vendored
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
var entries = []struct {
|
||||||
|
key string
|
||||||
|
value string
|
||||||
|
}{
|
||||||
|
{"1", "one"},
|
||||||
|
{"2", "two"},
|
||||||
|
{"3", "three"},
|
||||||
|
{"4", "four"},
|
||||||
|
{"5", "five"},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLRUCache(t *testing.T) {
|
||||||
|
c := NewLRUCache[string, string]()
|
||||||
|
|
||||||
|
for _, e := range entries {
|
||||||
|
c.Set(e.key, e.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Delete("missing")
|
||||||
|
_, ok := c.Get("missing")
|
||||||
|
assert.False(t, ok)
|
||||||
|
|
||||||
|
for _, e := range entries {
|
||||||
|
value, ok := c.Get(e.key)
|
||||||
|
if assert.True(t, ok) {
|
||||||
|
assert.Equal(t, e.value, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, e := range entries {
|
||||||
|
c.Delete(e.key)
|
||||||
|
|
||||||
|
_, ok := c.Get(e.key)
|
||||||
|
assert.False(t, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLRUMaxAge(t *testing.T) {
|
||||||
|
c := NewLRUCache[string, string](WithAge[string, string](86400))
|
||||||
|
|
||||||
|
now := time.Now().Unix()
|
||||||
|
expected := now + 86400
|
||||||
|
|
||||||
|
// Add one expired entry
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
c.lru.Back().Value.expires = now
|
||||||
|
|
||||||
|
// Reset
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
e := c.lru.Back().Value
|
||||||
|
assert.True(t, e.expires >= now)
|
||||||
|
c.lru.Back().Value.expires = now
|
||||||
|
|
||||||
|
// Set a few and verify expiration times
|
||||||
|
for _, s := range entries {
|
||||||
|
c.Set(s.key, s.value)
|
||||||
|
e := c.lru.Back().Value
|
||||||
|
assert.True(t, e.expires >= expected && e.expires <= expected+10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure we can get them all
|
||||||
|
for _, s := range entries {
|
||||||
|
_, ok := c.Get(s.key)
|
||||||
|
assert.True(t, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expire all entries
|
||||||
|
for _, s := range entries {
|
||||||
|
le, ok := c.cache[s.key]
|
||||||
|
if assert.True(t, ok) {
|
||||||
|
le.Value.expires = now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get one expired entry, which should clear all expired entries
|
||||||
|
_, ok := c.Get("3")
|
||||||
|
assert.False(t, ok)
|
||||||
|
assert.Equal(t, c.lru.Len(), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLRUpdateOnGet(t *testing.T) {
|
||||||
|
c := NewLRUCache[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
||||||
|
|
||||||
|
now := time.Now().Unix()
|
||||||
|
expires := now + 86400/2
|
||||||
|
|
||||||
|
// Add one expired entry
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
c.lru.Back().Value.expires = expires
|
||||||
|
|
||||||
|
_, ok := c.Get("foo")
|
||||||
|
assert.True(t, ok)
|
||||||
|
assert.True(t, c.lru.Back().Value.expires > expires)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMaxSize(t *testing.T) {
|
||||||
|
c := NewLRUCache[string, string](WithSize[string, string](2))
|
||||||
|
// Add one expired entry
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
_, ok := c.Get("foo")
|
||||||
|
assert.True(t, ok)
|
||||||
|
|
||||||
|
c.Set("bar", "foo")
|
||||||
|
c.Set("baz", "foo")
|
||||||
|
|
||||||
|
_, ok = c.Get("foo")
|
||||||
|
assert.False(t, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExist(t *testing.T) {
|
||||||
|
c := NewLRUCache[int, int](WithSize[int, int](1))
|
||||||
|
c.Set(1, 2)
|
||||||
|
assert.True(t, c.Exist(1))
|
||||||
|
c.Set(2, 3)
|
||||||
|
assert.False(t, c.Exist(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEvict(t *testing.T) {
|
||||||
|
temp := 0
|
||||||
|
evict := func(key int, value int) {
|
||||||
|
temp = key + value
|
||||||
|
}
|
||||||
|
|
||||||
|
c := NewLRUCache[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
||||||
|
c.Set(1, 2)
|
||||||
|
c.Set(2, 3)
|
||||||
|
|
||||||
|
assert.Equal(t, temp, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetWithExpire(t *testing.T) {
|
||||||
|
c := NewLRUCache[int, *struct{}](WithAge[int, *struct{}](1))
|
||||||
|
now := time.Now().Unix()
|
||||||
|
|
||||||
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
|
c.SetWithExpire(1, &struct{}{}, tenSecBefore)
|
||||||
|
|
||||||
|
// res is expected not to exist, and expires should be empty time.Time
|
||||||
|
res, expires, exist := c.GetWithExpire(1)
|
||||||
|
|
||||||
|
assert.True(t, nil == res)
|
||||||
|
assert.Equal(t, time.Time{}, expires)
|
||||||
|
assert.Equal(t, false, exist)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStale(t *testing.T) {
|
||||||
|
c := NewLRUCache[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
||||||
|
now := time.Now().Unix()
|
||||||
|
|
||||||
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
|
c.SetWithExpire(1, 2, tenSecBefore)
|
||||||
|
|
||||||
|
res, expires, exist := c.GetWithExpire(1)
|
||||||
|
assert.Equal(t, 2, res)
|
||||||
|
assert.Equal(t, tenSecBefore, expires)
|
||||||
|
assert.Equal(t, true, exist)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCloneTo(t *testing.T) {
|
||||||
|
o := NewLRUCache[string, int](WithSize[string, int](10))
|
||||||
|
o.Set("1", 1)
|
||||||
|
o.Set("2", 2)
|
||||||
|
|
||||||
|
n := NewLRUCache[string, int](WithSize[string, int](2))
|
||||||
|
n.Set("3", 3)
|
||||||
|
n.Set("4", 4)
|
||||||
|
|
||||||
|
o.CloneTo(n)
|
||||||
|
|
||||||
|
assert.False(t, n.Exist("3"))
|
||||||
|
assert.True(t, n.Exist("1"))
|
||||||
|
|
||||||
|
n.Set("5", 5)
|
||||||
|
assert.False(t, n.Exist("1"))
|
||||||
|
}
|
303
common/cert/cert.go
Normal file
303
common/cert/cert.go
Normal file
@ -0,0 +1,303 @@
|
|||||||
|
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
|
||||||
|
}
|
104
common/cert/cert_test.go
Normal file
104
common/cert/cert_test.go
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
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)
|
||||||
|
}
|
32
common/cert/storage.go
Normal file
32
common/cert/storage.go
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
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](),
|
||||||
|
}
|
||||||
|
}
|
35
common/cmd/cmd.go
Normal file
35
common/cmd/cmd.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ExecCmd(cmdStr string) (string, error) {
|
||||||
|
args := splitArgs(cmdStr)
|
||||||
|
|
||||||
|
var cmd *exec.Cmd
|
||||||
|
if len(args) == 1 {
|
||||||
|
cmd = exec.Command(args[0])
|
||||||
|
} else {
|
||||||
|
cmd = exec.Command(args[0], args[1:]...)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||||
|
}
|
||||||
|
return string(out), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitArgs(cmd string) []string {
|
||||||
|
args := strings.Split(cmd, " ")
|
||||||
|
|
||||||
|
// use in pipeline
|
||||||
|
if len(args) > 2 && strings.ContainsAny(cmd, "|") {
|
||||||
|
suffix := strings.Join(args[2:], " ")
|
||||||
|
args = append(args[:2], suffix)
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
}
|
40
common/cmd/cmd_test.go
Normal file
40
common/cmd/cmd_test.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSplitArgs(t *testing.T) {
|
||||||
|
args := splitArgs("ls")
|
||||||
|
args1 := splitArgs("ls -la")
|
||||||
|
args2 := splitArgs("bash -c ls")
|
||||||
|
args3 := splitArgs("bash -c ls -lahF | grep 'cmd'")
|
||||||
|
|
||||||
|
assert.Equal(t, 1, len(args))
|
||||||
|
assert.Equal(t, 2, len(args1))
|
||||||
|
assert.Equal(t, 3, len(args2))
|
||||||
|
assert.Equal(t, 3, len(args3))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecCmd(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
_, err := ExecCmd("dir")
|
||||||
|
assert.Nil(t, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := ExecCmd("ls")
|
||||||
|
_, err1 := ExecCmd("ls -la")
|
||||||
|
_, err2 := ExecCmd("bash -c ls")
|
||||||
|
_, err3 := ExecCmd("bash -c ls -la")
|
||||||
|
_, err4 := ExecCmd("bash -c ls -la | grep 'cmd'")
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Nil(t, err1)
|
||||||
|
assert.Nil(t, err2)
|
||||||
|
assert.Nil(t, err3)
|
||||||
|
assert.Nil(t, err4)
|
||||||
|
}
|
235
common/generics/list/list.go
Normal file
235
common/generics/list/list.go
Normal file
@ -0,0 +1,235 @@
|
|||||||
|
// Copyright 2009 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Package list implements a doubly linked list.
|
||||||
|
//
|
||||||
|
// To iterate over a list (where l is a *List):
|
||||||
|
// for e := l.Front(); e != nil; e = e.Next() {
|
||||||
|
// // do something with e.Value
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
package list
|
||||||
|
|
||||||
|
// Element is an element of a linked list.
|
||||||
|
type Element[T any] struct {
|
||||||
|
// Next and previous pointers in the doubly-linked list of elements.
|
||||||
|
// To simplify the implementation, internally a list l is implemented
|
||||||
|
// as a ring, such that &l.root is both the next element of the last
|
||||||
|
// list element (l.Back()) and the previous element of the first list
|
||||||
|
// element (l.Front()).
|
||||||
|
next, prev *Element[T]
|
||||||
|
|
||||||
|
// The list to which this element belongs.
|
||||||
|
list *List[T]
|
||||||
|
|
||||||
|
// The value stored with this element.
|
||||||
|
Value T
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next returns the next list element or nil.
|
||||||
|
func (e *Element[T]) Next() *Element[T] {
|
||||||
|
if p := e.next; e.list != nil && p != &e.list.root {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prev returns the previous list element or nil.
|
||||||
|
func (e *Element[T]) Prev() *Element[T] {
|
||||||
|
if p := e.prev; e.list != nil && p != &e.list.root {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// List represents a doubly linked list.
|
||||||
|
// The zero value for List is an empty list ready to use.
|
||||||
|
type List[T any] struct {
|
||||||
|
root Element[T] // sentinel list element, only &root, root.prev, and root.next are used
|
||||||
|
len int // current list length excluding (this) sentinel element
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init initializes or clears list l.
|
||||||
|
func (l *List[T]) Init() *List[T] {
|
||||||
|
l.root.next = &l.root
|
||||||
|
l.root.prev = &l.root
|
||||||
|
l.len = 0
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns an initialized list.
|
||||||
|
func New[T any]() *List[T] { return new(List[T]).Init() }
|
||||||
|
|
||||||
|
// Len returns the number of elements of list l.
|
||||||
|
// The complexity is O(1).
|
||||||
|
func (l *List[T]) Len() int { return l.len }
|
||||||
|
|
||||||
|
// Front returns the first element of list l or nil if the list is empty.
|
||||||
|
func (l *List[T]) Front() *Element[T] {
|
||||||
|
if l.len == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return l.root.next
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back returns the last element of list l or nil if the list is empty.
|
||||||
|
func (l *List[T]) Back() *Element[T] {
|
||||||
|
if l.len == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return l.root.prev
|
||||||
|
}
|
||||||
|
|
||||||
|
// lazyInit lazily initializes a zero List value.
|
||||||
|
func (l *List[T]) lazyInit() {
|
||||||
|
if l.root.next == nil {
|
||||||
|
l.Init()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert inserts e after at, increments l.len, and returns e.
|
||||||
|
func (l *List[T]) insert(e, at *Element[T]) *Element[T] {
|
||||||
|
e.prev = at
|
||||||
|
e.next = at.next
|
||||||
|
e.prev.next = e
|
||||||
|
e.next.prev = e
|
||||||
|
e.list = l
|
||||||
|
l.len++
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
|
||||||
|
func (l *List[T]) insertValue(v T, at *Element[T]) *Element[T] {
|
||||||
|
return l.insert(&Element[T]{Value: v}, at)
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove removes e from its list, decrements l.len
|
||||||
|
func (l *List[T]) remove(e *Element[T]) {
|
||||||
|
e.prev.next = e.next
|
||||||
|
e.next.prev = e.prev
|
||||||
|
e.next = nil // avoid memory leaks
|
||||||
|
e.prev = nil // avoid memory leaks
|
||||||
|
e.list = nil
|
||||||
|
l.len--
|
||||||
|
}
|
||||||
|
|
||||||
|
// move moves e to next to at.
|
||||||
|
func (l *List[T]) move(e, at *Element[T]) {
|
||||||
|
if e == at {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.prev.next = e.next
|
||||||
|
e.next.prev = e.prev
|
||||||
|
|
||||||
|
e.prev = at
|
||||||
|
e.next = at.next
|
||||||
|
e.prev.next = e
|
||||||
|
e.next.prev = e
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove removes e from l if e is an element of list l.
|
||||||
|
// It returns the element value e.Value.
|
||||||
|
// The element must not be nil.
|
||||||
|
func (l *List[T]) Remove(e *Element[T]) T {
|
||||||
|
if e.list == l {
|
||||||
|
// if e.list == l, l must have been initialized when e was inserted
|
||||||
|
// in l or l == nil (e is a zero Element) and l.remove will crash
|
||||||
|
l.remove(e)
|
||||||
|
}
|
||||||
|
return e.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushFront inserts a new element e with value v at the front of list l and returns e.
|
||||||
|
func (l *List[T]) PushFront(v T) *Element[T] {
|
||||||
|
l.lazyInit()
|
||||||
|
return l.insertValue(v, &l.root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushBack inserts a new element e with value v at the back of list l and returns e.
|
||||||
|
func (l *List[T]) PushBack(v T) *Element[T] {
|
||||||
|
l.lazyInit()
|
||||||
|
return l.insertValue(v, l.root.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InsertBefore inserts a new element e with value v immediately before mark and returns e.
|
||||||
|
// If mark is not an element of l, the list is not modified.
|
||||||
|
// The mark must not be nil.
|
||||||
|
func (l *List[T]) InsertBefore(v T, mark *Element[T]) *Element[T] {
|
||||||
|
if mark.list != l {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
return l.insertValue(v, mark.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InsertAfter inserts a new element e with value v immediately after mark and returns e.
|
||||||
|
// If mark is not an element of l, the list is not modified.
|
||||||
|
// The mark must not be nil.
|
||||||
|
func (l *List[T]) InsertAfter(v T, mark *Element[T]) *Element[T] {
|
||||||
|
if mark.list != l {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
return l.insertValue(v, mark)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveToFront moves element e to the front of list l.
|
||||||
|
// If e is not an element of l, the list is not modified.
|
||||||
|
// The element must not be nil.
|
||||||
|
func (l *List[T]) MoveToFront(e *Element[T]) {
|
||||||
|
if e.list != l || l.root.next == e {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
l.move(e, &l.root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveToBack moves element e to the back of list l.
|
||||||
|
// If e is not an element of l, the list is not modified.
|
||||||
|
// The element must not be nil.
|
||||||
|
func (l *List[T]) MoveToBack(e *Element[T]) {
|
||||||
|
if e.list != l || l.root.prev == e {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// see comment in List.Remove about initialization of l
|
||||||
|
l.move(e, l.root.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveBefore moves element e to its new position before mark.
|
||||||
|
// If e or mark is not an element of l, or e == mark, the list is not modified.
|
||||||
|
// The element and mark must not be nil.
|
||||||
|
func (l *List[T]) MoveBefore(e, mark *Element[T]) {
|
||||||
|
if e.list != l || e == mark || mark.list != l {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.move(e, mark.prev)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveAfter moves element e to its new position after mark.
|
||||||
|
// If e or mark is not an element of l, or e == mark, the list is not modified.
|
||||||
|
// The element and mark must not be nil.
|
||||||
|
func (l *List[T]) MoveAfter(e, mark *Element[T]) {
|
||||||
|
if e.list != l || e == mark || mark.list != l {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.move(e, mark)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushBackList inserts a copy of another list at the back of list l.
|
||||||
|
// The lists l and other may be the same. They must not be nil.
|
||||||
|
func (l *List[T]) PushBackList(other *List[T]) {
|
||||||
|
l.lazyInit()
|
||||||
|
for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
|
||||||
|
l.insertValue(e.Value, l.root.prev)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushFrontList inserts a copy of another list at the front of list l.
|
||||||
|
// The lists l and other may be the same. They must not be nil.
|
||||||
|
func (l *List[T]) PushFrontList(other *List[T]) {
|
||||||
|
l.lazyInit()
|
||||||
|
for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
|
||||||
|
l.insertValue(e.Value, &l.root)
|
||||||
|
}
|
||||||
|
}
|
@ -4,6 +4,7 @@ package murmur3
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"hash"
|
"hash"
|
||||||
|
"math/bits"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -54,11 +55,11 @@ func (d *digest32) bmix(p []byte) (tail []byte) {
|
|||||||
k1 := *(*uint32)(unsafe.Pointer(&p[i*4]))
|
k1 := *(*uint32)(unsafe.Pointer(&p[i*4]))
|
||||||
|
|
||||||
k1 *= c1_32
|
k1 *= c1_32
|
||||||
k1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15)
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
k1 *= c2_32
|
k1 *= c2_32
|
||||||
|
|
||||||
h1 ^= k1
|
h1 ^= k1
|
||||||
h1 = (h1 << 13) | (h1 >> 19) // rotl32(h1, 13)
|
h1 = bits.RotateLeft32(h1, 13)
|
||||||
h1 = h1*4 + h1 + 0xe6546b64
|
h1 = h1*4 + h1 + 0xe6546b64
|
||||||
}
|
}
|
||||||
d.h1 = h1
|
d.h1 = h1
|
||||||
@ -66,7 +67,6 @@ func (d *digest32) bmix(p []byte) (tail []byte) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *digest32) Sum32() (h1 uint32) {
|
func (d *digest32) Sum32() (h1 uint32) {
|
||||||
|
|
||||||
h1 = d.h1
|
h1 = d.h1
|
||||||
|
|
||||||
var k1 uint32
|
var k1 uint32
|
||||||
@ -80,7 +80,7 @@ func (d *digest32) Sum32() (h1 uint32) {
|
|||||||
case 1:
|
case 1:
|
||||||
k1 ^= uint32(d.tail[0])
|
k1 ^= uint32(d.tail[0])
|
||||||
k1 *= c1_32
|
k1 *= c1_32
|
||||||
k1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15)
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
k1 *= c2_32
|
k1 *= c2_32
|
||||||
h1 ^= k1
|
h1 ^= k1
|
||||||
}
|
}
|
||||||
@ -102,20 +102,15 @@ func Sum32WithSeed(data []byte, seed uint32) uint32 {
|
|||||||
h1 := seed
|
h1 := seed
|
||||||
|
|
||||||
nblocks := len(data) / 4
|
nblocks := len(data) / 4
|
||||||
var p uintptr
|
for i := 0; i < nblocks; i++ {
|
||||||
if len(data) > 0 {
|
k1 := *(*uint32)(unsafe.Pointer(&data[i*4]))
|
||||||
p = uintptr(unsafe.Pointer(&data[0]))
|
|
||||||
}
|
|
||||||
p1 := p + uintptr(4*nblocks)
|
|
||||||
for ; p < p1; p += 4 {
|
|
||||||
k1 := *(*uint32)(unsafe.Pointer(p))
|
|
||||||
|
|
||||||
k1 *= c1_32
|
k1 *= c1_32
|
||||||
k1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15)
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
k1 *= c2_32
|
k1 *= c2_32
|
||||||
|
|
||||||
h1 ^= k1
|
h1 ^= k1
|
||||||
h1 = (h1 << 13) | (h1 >> 19) // rotl32(h1, 13)
|
h1 = bits.RotateLeft32(h1, 13)
|
||||||
h1 = h1*4 + h1 + 0xe6546b64
|
h1 = h1*4 + h1 + 0xe6546b64
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -132,7 +127,7 @@ func Sum32WithSeed(data []byte, seed uint32) uint32 {
|
|||||||
case 1:
|
case 1:
|
||||||
k1 ^= uint32(tail[0])
|
k1 ^= uint32(tail[0])
|
||||||
k1 *= c1_32
|
k1 *= c1_32
|
||||||
k1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15)
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
k1 *= c2_32
|
k1 *= c2_32
|
||||||
h1 ^= k1
|
h1 ^= k1
|
||||||
}
|
}
|
||||||
|
44
common/net/bufconn.go
Normal file
44
common/net/bufconn.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BufferedConn struct {
|
||||||
|
r *bufio.Reader
|
||||||
|
net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBufferedConn(c net.Conn) *BufferedConn {
|
||||||
|
if bc, ok := c.(*BufferedConn); ok {
|
||||||
|
return bc
|
||||||
|
}
|
||||||
|
return &BufferedConn{bufio.NewReader(c), c}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reader returns the internal bufio.Reader.
|
||||||
|
func (c *BufferedConn) Reader() *bufio.Reader {
|
||||||
|
return c.r
|
||||||
|
}
|
||||||
|
|
||||||
|
// Peek returns the next n bytes without advancing the reader.
|
||||||
|
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
||||||
|
return c.r.Peek(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Read(p []byte) (int, error) {
|
||||||
|
return c.r.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ReadByte() (byte, error) {
|
||||||
|
return c.r.ReadByte()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) UnreadByte() error {
|
||||||
|
return c.r.UnreadByte()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Buffered() int {
|
||||||
|
return c.r.Buffered()
|
||||||
|
}
|
11
common/net/io.go
Normal file
11
common/net/io.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import "io"
|
||||||
|
|
||||||
|
type ReadOnlyReader struct {
|
||||||
|
io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
type WriteOnlyWriter struct {
|
||||||
|
io.Writer
|
||||||
|
}
|
39
common/net/relay.go
Normal file
39
common/net/relay.go
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
ch := make(chan error)
|
||||||
|
|
||||||
|
tcpKeepAlive(leftConn)
|
||||||
|
tcpKeepAlive(rightConn)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
|
_ = pool.Put(buf)
|
||||||
|
_ = leftConn.SetReadDeadline(time.Now())
|
||||||
|
ch <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
|
_, _ = io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
|
_ = pool.Put(buf)
|
||||||
|
_ = rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
}
|
||||||
|
}
|
53
common/nnip/netip.go
Normal file
53
common/nnip/netip.go
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
package nnip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IpToAddr converts the net.IP to netip.Addr.
|
||||||
|
// If slice's length is not 4 or 16, IpToAddr returns netip.Addr{}
|
||||||
|
func IpToAddr(slice net.IP) netip.Addr {
|
||||||
|
ip := slice
|
||||||
|
if len(ip) != 4 {
|
||||||
|
if ip = slice.To4(); ip == nil {
|
||||||
|
ip = slice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if addr, ok := netip.AddrFromSlice(ip); ok {
|
||||||
|
return addr
|
||||||
|
}
|
||||||
|
return netip.Addr{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnMasked returns p's last IP address.
|
||||||
|
// If p is invalid, UnMasked returns netip.Addr{}
|
||||||
|
func UnMasked(p netip.Prefix) netip.Addr {
|
||||||
|
if !p.IsValid() {
|
||||||
|
return netip.Addr{}
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := p.Addr().As16()
|
||||||
|
|
||||||
|
hi := binary.BigEndian.Uint64(buf[:8])
|
||||||
|
lo := binary.BigEndian.Uint64(buf[8:])
|
||||||
|
|
||||||
|
bits := p.Bits()
|
||||||
|
if bits <= 32 {
|
||||||
|
bits += 96
|
||||||
|
}
|
||||||
|
|
||||||
|
hi = hi | ^uint64(0)>>bits
|
||||||
|
lo = lo | ^(^uint64(0) << (128 - bits))
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint64(buf[:8], hi)
|
||||||
|
binary.BigEndian.PutUint64(buf[8:], lo)
|
||||||
|
|
||||||
|
addr := netip.AddrFrom16(buf)
|
||||||
|
if p.Addr().Is4() {
|
||||||
|
return addr.Unmap()
|
||||||
|
}
|
||||||
|
return addr
|
||||||
|
}
|
@ -1,3 +1,3 @@
|
|||||||
package observable
|
package observable
|
||||||
|
|
||||||
type Iterable <-chan interface{}
|
type Iterable[T any] <-chan T
|
||||||
|
@ -5,62 +5,60 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Observable struct {
|
type Observable[T any] struct {
|
||||||
iterable Iterable
|
iterable Iterable[T]
|
||||||
listener *sync.Map
|
listener map[Subscription[T]]*Subscriber[T]
|
||||||
|
mux sync.Mutex
|
||||||
done bool
|
done bool
|
||||||
doneLock sync.RWMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) process() {
|
func (o *Observable[T]) process() {
|
||||||
for item := range o.iterable {
|
for item := range o.iterable {
|
||||||
o.listener.Range(func(key, value interface{}) bool {
|
o.mux.Lock()
|
||||||
elm := value.(*Subscriber)
|
for _, sub := range o.listener {
|
||||||
elm.Emit(item)
|
sub.Emit(item)
|
||||||
return true
|
}
|
||||||
})
|
o.mux.Unlock()
|
||||||
}
|
}
|
||||||
o.close()
|
o.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) close() {
|
func (o *Observable[T]) close() {
|
||||||
o.doneLock.Lock()
|
o.mux.Lock()
|
||||||
o.done = true
|
defer o.mux.Unlock()
|
||||||
o.doneLock.Unlock()
|
|
||||||
|
|
||||||
o.listener.Range(func(key, value interface{}) bool {
|
o.done = true
|
||||||
elm := value.(*Subscriber)
|
for _, sub := range o.listener {
|
||||||
elm.Close()
|
sub.Close()
|
||||||
return true
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) Subscribe() (Subscription, error) {
|
func (o *Observable[T]) Subscribe() (Subscription[T], error) {
|
||||||
o.doneLock.RLock()
|
o.mux.Lock()
|
||||||
done := o.done
|
defer o.mux.Unlock()
|
||||||
o.doneLock.RUnlock()
|
if o.done {
|
||||||
if done == true {
|
return nil, errors.New("observable is closed")
|
||||||
return nil, errors.New("Observable is closed")
|
|
||||||
}
|
}
|
||||||
subscriber := newSubscriber()
|
subscriber := newSubscriber[T]()
|
||||||
o.listener.Store(subscriber.Out(), subscriber)
|
o.listener[subscriber.Out()] = subscriber
|
||||||
return subscriber.Out(), nil
|
return subscriber.Out(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) UnSubscribe(sub Subscription) {
|
func (o *Observable[T]) UnSubscribe(sub Subscription[T]) {
|
||||||
elm, exist := o.listener.Load(sub)
|
o.mux.Lock()
|
||||||
|
defer o.mux.Unlock()
|
||||||
|
subscriber, exist := o.listener[sub]
|
||||||
if !exist {
|
if !exist {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
subscriber := elm.(*Subscriber)
|
delete(o.listener, sub)
|
||||||
o.listener.Delete(subscriber.Out())
|
|
||||||
subscriber.Close()
|
subscriber.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewObservable(any Iterable) *Observable {
|
func NewObservable[T any](iter Iterable[T]) *Observable[T] {
|
||||||
observable := &Observable{
|
observable := &Observable[T]{
|
||||||
iterable: any,
|
iterable: iter,
|
||||||
listener: &sync.Map{},
|
listener: map[Subscription[T]]*Subscriber[T]{},
|
||||||
}
|
}
|
||||||
go observable.process()
|
go observable.process()
|
||||||
return observable
|
return observable
|
||||||
|
@ -1,14 +1,16 @@
|
|||||||
package observable
|
package observable
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"runtime"
|
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator(item []interface{}) chan interface{} {
|
func iterator[T any](item []T) chan T {
|
||||||
ch := make(chan interface{})
|
ch := make(chan T)
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(100 * time.Millisecond)
|
time.Sleep(100 * time.Millisecond)
|
||||||
for _, elm := range item {
|
for _, elm := range item {
|
||||||
@ -20,86 +22,71 @@ func iterator(item []interface{}) chan interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable(t *testing.T) {
|
func TestObservable(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator[int]([]int{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable[int](iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
count := 0
|
count := 0
|
||||||
for range data {
|
for range data {
|
||||||
count = count + 1
|
count++
|
||||||
}
|
|
||||||
if count != 5 {
|
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
}
|
||||||
|
assert.Equal(t, count, 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_MutilSubscribe(t *testing.T) {
|
func TestObservable_MultiSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator[int]([]int{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable[int](iter)
|
||||||
ch1, _ := src.Subscribe()
|
ch1, _ := src.Subscribe()
|
||||||
ch2, _ := src.Subscribe()
|
ch2, _ := src.Subscribe()
|
||||||
count := 0
|
count := atomic.NewInt32(0)
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan int) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count = count + 1
|
count.Inc()
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
go waitCh(ch1)
|
go waitCh(ch1)
|
||||||
go waitCh(ch2)
|
go waitCh(ch2)
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
if count != 10 {
|
assert.Equal(t, int32(10), count.Load())
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribe(t *testing.T) {
|
func TestObservable_UnSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator[int]([]int{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable[int](iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
src.UnSubscribe(data)
|
src.UnSubscribe(data)
|
||||||
_, open := <-data
|
_, open := <-data
|
||||||
if open {
|
assert.False(t, open)
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1})
|
iter := iterator[int]([]int{1})
|
||||||
src := NewObservable(iter)
|
src := NewObservable[int](iter)
|
||||||
data, _ := src.Subscribe()
|
data, _ := src.Subscribe()
|
||||||
<-data
|
<-data
|
||||||
|
|
||||||
_, closed := src.Subscribe()
|
_, closed := src.Subscribe()
|
||||||
if closed == nil {
|
assert.NotNil(t, closed)
|
||||||
t.Error("Observable should be closed")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
||||||
sub := Subscription(make(chan interface{}))
|
sub := Subscription[int](make(chan int))
|
||||||
iter := iterator([]interface{}{1})
|
iter := iterator[int]([]int{1})
|
||||||
src := NewObservable(iter)
|
src := NewObservable[int](iter)
|
||||||
src.UnSubscribe(sub)
|
src.UnSubscribe(sub)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
||||||
// waiting for other goroutine recycle
|
iter := iterator[int]([]int{1, 2, 3, 4, 5})
|
||||||
time.Sleep(120 * time.Millisecond)
|
src := NewObservable[int](iter)
|
||||||
init := runtime.NumGoroutine()
|
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
|
||||||
src := NewObservable(iter)
|
|
||||||
max := 100
|
max := 100
|
||||||
|
|
||||||
var list []Subscription
|
var list []Subscription[int]
|
||||||
for i := 0; i < max; i++ {
|
for i := 0; i < max; i++ {
|
||||||
ch, _ := src.Subscribe()
|
ch, _ := src.Subscribe()
|
||||||
list = append(list, ch)
|
list = append(list, ch)
|
||||||
@ -107,7 +94,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(max)
|
wg.Add(max)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan int) {
|
||||||
for range ch {
|
for range ch {
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
@ -117,8 +104,43 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
go waitCh(ch)
|
go waitCh(ch)
|
||||||
}
|
}
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
now := runtime.NumGoroutine()
|
|
||||||
if init != now {
|
for _, sub := range list {
|
||||||
t.Errorf("Goroutine Leak: init %d now %d", init, now)
|
_, more := <-sub
|
||||||
|
assert.False(t, more)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_, more := <-list[0]
|
||||||
|
assert.False(t, more)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Benchmark_Observable_1000(b *testing.B) {
|
||||||
|
ch := make(chan int)
|
||||||
|
o := NewObservable[int](ch)
|
||||||
|
num := 1000
|
||||||
|
|
||||||
|
subs := []Subscription[int]{}
|
||||||
|
for i := 0; i < num; i++ {
|
||||||
|
sub, _ := o.Subscribe()
|
||||||
|
subs = append(subs, sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(num)
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for _, sub := range subs {
|
||||||
|
go func(s Subscription[int]) {
|
||||||
|
for range s {
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}(sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
ch <- i
|
||||||
|
}
|
||||||
|
|
||||||
|
close(ch)
|
||||||
|
wg.Wait()
|
||||||
}
|
}
|
||||||
|
@ -2,34 +2,32 @@ package observable
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"gopkg.in/eapache/channels.v1"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Subscription <-chan interface{}
|
type Subscription[T any] <-chan T
|
||||||
|
|
||||||
type Subscriber struct {
|
type Subscriber[T any] struct {
|
||||||
buffer *channels.InfiniteChannel
|
buffer chan T
|
||||||
once sync.Once
|
once sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Emit(item interface{}) {
|
func (s *Subscriber[T]) Emit(item T) {
|
||||||
s.buffer.In() <- item
|
s.buffer <- item
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Out() Subscription {
|
func (s *Subscriber[T]) Out() Subscription[T] {
|
||||||
return s.buffer.Out()
|
return s.buffer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Close() {
|
func (s *Subscriber[T]) Close() {
|
||||||
s.once.Do(func() {
|
s.once.Do(func() {
|
||||||
s.buffer.Close()
|
close(s.buffer)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func newSubscriber() *Subscriber {
|
func newSubscriber[T any]() *Subscriber[T] {
|
||||||
sub := &Subscriber{
|
sub := &Subscriber[T]{
|
||||||
buffer: channels.NewInfiniteChannel(),
|
buffer: make(chan T, 200),
|
||||||
}
|
}
|
||||||
return sub
|
return sub
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,80 @@
|
|||||||
package picker
|
package picker
|
||||||
|
|
||||||
import "context"
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Picker provides synchronization, and Context cancelation
|
||||||
|
// for groups of goroutines working on subtasks of a common task.
|
||||||
|
// Inspired by errGroup
|
||||||
|
type Picker[T any] struct {
|
||||||
|
ctx context.Context
|
||||||
|
cancel func()
|
||||||
|
|
||||||
|
wg sync.WaitGroup
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
errOnce sync.Once
|
||||||
|
result T
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPicker[T any](ctx context.Context, cancel func()) *Picker[T] {
|
||||||
|
return &Picker[T]{
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithContext returns a new Picker and an associated Context derived from ctx.
|
||||||
|
// and cancel when first element return.
|
||||||
|
func WithContext[T any](ctx context.Context) (*Picker[T], context.Context) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
return newPicker[T](ctx, cancel), ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithTimeout returns a new Picker and an associated Context derived from ctx with timeout.
|
||||||
|
func WithTimeout[T any](ctx context.Context, timeout time.Duration) (*Picker[T], context.Context) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
return newPicker[T](ctx, cancel), ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait blocks until all function calls from the Go method have returned,
|
||||||
|
// then returns the first nil error result (if any) from them.
|
||||||
|
func (p *Picker[T]) Wait() T {
|
||||||
|
p.wg.Wait()
|
||||||
|
if p.cancel != nil {
|
||||||
|
p.cancel()
|
||||||
|
}
|
||||||
|
return p.result
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error return the first error (if all success return nil)
|
||||||
|
func (p *Picker[T]) Error() error {
|
||||||
|
return p.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go calls the given function in a new goroutine.
|
||||||
|
// The first call to return a nil error cancels the group; its result will be returned by Wait.
|
||||||
|
func (p *Picker[T]) Go(f func() (T, error)) {
|
||||||
|
p.wg.Add(1)
|
||||||
|
|
||||||
func SelectFast(ctx context.Context, in <-chan interface{}) <-chan interface{} {
|
|
||||||
out := make(chan interface{})
|
|
||||||
go func() {
|
go func() {
|
||||||
select {
|
defer p.wg.Done()
|
||||||
case p, open := <-in:
|
|
||||||
if open {
|
|
||||||
out <- p
|
|
||||||
}
|
|
||||||
case <-ctx.Done():
|
|
||||||
}
|
|
||||||
|
|
||||||
close(out)
|
if ret, err := f(); err == nil {
|
||||||
for range in {
|
p.once.Do(func() {
|
||||||
|
p.result = ret
|
||||||
|
if p.cancel != nil {
|
||||||
|
p.cancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
p.errOnce.Do(func() {
|
||||||
|
p.err = err
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
}
|
||||||
|
@ -4,41 +4,42 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func sleepAndSend(delay int, in chan<- interface{}, input interface{}) {
|
func sleepAndSend[T any](ctx context.Context, delay int, input T) func() (T, error) {
|
||||||
time.Sleep(time.Millisecond * time.Duration(delay))
|
return func() (T, error) {
|
||||||
in <- input
|
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
||||||
}
|
select {
|
||||||
|
case <-timer.C:
|
||||||
func sleepAndClose(delay int, in chan interface{}) {
|
return input, nil
|
||||||
time.Sleep(time.Millisecond * time.Duration(delay))
|
case <-ctx.Done():
|
||||||
close(in)
|
return getZero[T](), ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPicker_Basic(t *testing.T) {
|
func TestPicker_Basic(t *testing.T) {
|
||||||
in := make(chan interface{})
|
picker, ctx := WithContext[int](context.Background())
|
||||||
fast := SelectFast(context.Background(), in)
|
picker.Go(sleepAndSend(ctx, 30, 2))
|
||||||
go sleepAndSend(20, in, 1)
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
go sleepAndSend(30, in, 2)
|
|
||||||
go sleepAndClose(40, in)
|
|
||||||
|
|
||||||
number, exist := <-fast
|
number := picker.Wait()
|
||||||
if !exist || number != 1 {
|
assert.NotNil(t, number)
|
||||||
t.Error("should recv 1", exist, number)
|
assert.Equal(t, number, 1)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPicker_Timeout(t *testing.T) {
|
func TestPicker_Timeout(t *testing.T) {
|
||||||
in := make(chan interface{})
|
picker, ctx := WithTimeout[int](context.Background(), time.Millisecond*5)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
defer cancel()
|
|
||||||
fast := SelectFast(ctx, in)
|
|
||||||
go sleepAndSend(20, in, 1)
|
|
||||||
go sleepAndClose(30, in)
|
|
||||||
|
|
||||||
_, exist := <-fast
|
number := picker.Wait()
|
||||||
if exist {
|
assert.Equal(t, number, getZero[int]())
|
||||||
t.Error("should recv false")
|
assert.NotNil(t, picker.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getZero[T any]() T {
|
||||||
|
var result T
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
64
common/pool/alloc.go
Normal file
64
common/pool/alloc.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
// Inspired by https://github.com/xtaci/smux/blob/master/alloc.go
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"math/bits"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var defaultAllocator = NewAllocator()
|
||||||
|
|
||||||
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
|
type Allocator struct {
|
||||||
|
buffers []sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
|
||||||
|
// the waste(memory fragmentation) of space allocation is guaranteed to be
|
||||||
|
// no more than 50%.
|
||||||
|
func NewAllocator() *Allocator {
|
||||||
|
alloc := new(Allocator)
|
||||||
|
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
||||||
|
for k := range alloc.buffers {
|
||||||
|
i := k
|
||||||
|
alloc.buffers[k].New = func() any {
|
||||||
|
return make([]byte, 1<<uint32(i))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return alloc
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get a []byte from pool with most appropriate cap
|
||||||
|
func (alloc *Allocator) Get(size int) []byte {
|
||||||
|
if size <= 0 || size > 65536 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
bits := msb(size)
|
||||||
|
if size == 1<<bits {
|
||||||
|
return alloc.buffers[bits].Get().([]byte)[:size]
|
||||||
|
}
|
||||||
|
|
||||||
|
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put returns a []byte to pool for future use,
|
||||||
|
// which the cap must be exactly 2^n
|
||||||
|
func (alloc *Allocator) Put(buf []byte) error {
|
||||||
|
bits := msb(cap(buf))
|
||||||
|
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
|
||||||
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
|
}
|
||||||
|
|
||||||
|
//lint:ignore SA6002 ignore temporarily
|
||||||
|
//nolint
|
||||||
|
alloc.buffers[bits].Put(buf)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// msb return the pos of most significant bit
|
||||||
|
func msb(size int) uint16 {
|
||||||
|
return uint16(bits.Len32(uint32(size)) - 1)
|
||||||
|
}
|
48
common/pool/alloc_test.go
Normal file
48
common/pool/alloc_test.go
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAllocGet(t *testing.T) {
|
||||||
|
alloc := NewAllocator()
|
||||||
|
assert.Nil(t, alloc.Get(0))
|
||||||
|
assert.Equal(t, 1, len(alloc.Get(1)))
|
||||||
|
assert.Equal(t, 2, len(alloc.Get(2)))
|
||||||
|
assert.Equal(t, 3, len(alloc.Get(3)))
|
||||||
|
assert.Equal(t, 4, cap(alloc.Get(3)))
|
||||||
|
assert.Equal(t, 4, cap(alloc.Get(4)))
|
||||||
|
assert.Equal(t, 1023, len(alloc.Get(1023)))
|
||||||
|
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
||||||
|
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
||||||
|
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
||||||
|
assert.Nil(t, alloc.Get(65537))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAllocPut(t *testing.T) {
|
||||||
|
alloc := NewAllocator()
|
||||||
|
assert.NotNil(t, alloc.Put(nil), "put nil misbehavior")
|
||||||
|
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
|
||||||
|
assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
|
||||||
|
assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
|
||||||
|
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
|
||||||
|
assert.NotNil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAllocPutThenGet(t *testing.T) {
|
||||||
|
alloc := NewAllocator()
|
||||||
|
data := alloc.Get(4)
|
||||||
|
alloc.Put(data)
|
||||||
|
newData := alloc.Get(4)
|
||||||
|
|
||||||
|
assert.Equal(t, cap(data), cap(newData), "different cap while alloc.Get()")
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkMSB(b *testing.B) {
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
msb(rand.Int())
|
||||||
|
}
|
||||||
|
}
|
17
common/pool/buffer.go
Normal file
17
common/pool/buffer.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var bufferPool = sync.Pool{New: func() any { return &bytes.Buffer{} }}
|
||||||
|
|
||||||
|
func GetBuffer() *bytes.Buffer {
|
||||||
|
return bufferPool.Get().(*bytes.Buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PutBuffer(buf *bytes.Buffer) {
|
||||||
|
buf.Reset()
|
||||||
|
bufferPool.Put(buf)
|
||||||
|
}
|
@ -1,15 +1,21 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// io.Copy default buffer size is 32 KiB
|
// io.Copy default buffer size is 32 KiB
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
bufferSize = 20 * 1024
|
RelayBufferSize = 20 * 1024
|
||||||
|
|
||||||
|
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
||||||
|
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
||||||
|
// set to 9000, so the UDP Buffer size set to 16Kib
|
||||||
|
UDPBufferSize = 16 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
// BufPool provide buffer for relay
|
func Get(size int) []byte {
|
||||||
var BufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
|
return defaultAllocator.Get(size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Put(buf []byte) error {
|
||||||
|
return defaultAllocator.Put(buf)
|
||||||
|
}
|
||||||
|
@ -5,13 +5,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Queue is a simple concurrent safe queue
|
// Queue is a simple concurrent safe queue
|
||||||
type Queue struct {
|
type Queue[T any] struct {
|
||||||
items []interface{}
|
items []T
|
||||||
lock sync.RWMutex
|
lock sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put add the item to the queue.
|
// Put add the item to the queue.
|
||||||
func (q *Queue) Put(items ...interface{}) {
|
func (q *Queue[T]) Put(items ...T) {
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -22,9 +22,9 @@ func (q *Queue) Put(items ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pop returns the head of items.
|
// Pop returns the head of items.
|
||||||
func (q *Queue) Pop() interface{} {
|
func (q *Queue[T]) Pop() T {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return nil
|
return GetZero[T]()
|
||||||
}
|
}
|
||||||
|
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
@ -34,21 +34,21 @@ func (q *Queue) Pop() interface{} {
|
|||||||
return head
|
return head
|
||||||
}
|
}
|
||||||
|
|
||||||
// First returns the head of items without deleting.
|
// Last returns the last of item.
|
||||||
func (q *Queue) First() interface{} {
|
func (q *Queue[T]) Last() T {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return nil
|
return GetZero[T]()
|
||||||
}
|
}
|
||||||
|
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
head := q.items[0]
|
last := q.items[len(q.items)-1]
|
||||||
q.lock.RUnlock()
|
q.lock.RUnlock()
|
||||||
return head
|
return last
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy get the copy of queue.
|
// Copy get the copy of queue.
|
||||||
func (q *Queue) Copy() []interface{} {
|
func (q *Queue[T]) Copy() []T {
|
||||||
items := []interface{}{}
|
items := []T{}
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
items = append(items, q.items...)
|
items = append(items, q.items...)
|
||||||
q.lock.RUnlock()
|
q.lock.RUnlock()
|
||||||
@ -56,7 +56,7 @@ func (q *Queue) Copy() []interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Len returns the number of items in this queue.
|
// Len returns the number of items in this queue.
|
||||||
func (q *Queue) Len() int64 {
|
func (q *Queue[T]) Len() int64 {
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
defer q.lock.Unlock()
|
defer q.lock.Unlock()
|
||||||
|
|
||||||
@ -64,8 +64,13 @@ func (q *Queue) Len() int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New is a constructor for a new concurrent safe queue.
|
// New is a constructor for a new concurrent safe queue.
|
||||||
func New(hint int64) *Queue {
|
func New[T any](hint int64) *Queue[T] {
|
||||||
return &Queue{
|
return &Queue[T]{
|
||||||
items: make([]interface{}, 0, hint),
|
items: make([]T, 0, hint),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetZero[T any]() T {
|
||||||
|
var result T
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
64
common/singledo/singledo.go
Normal file
64
common/singledo/singledo.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package singledo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type call[T any] struct {
|
||||||
|
wg sync.WaitGroup
|
||||||
|
val T
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Single[T any] struct {
|
||||||
|
mux sync.Mutex
|
||||||
|
last time.Time
|
||||||
|
wait time.Duration
|
||||||
|
call *call[T]
|
||||||
|
result *Result[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result[T any] struct {
|
||||||
|
Val T
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do single.Do likes sync.singleFlight
|
||||||
|
//lint:ignore ST1008 it likes sync.singleFlight
|
||||||
|
func (s *Single[T]) Do(fn func() (T, error)) (v T, err error, shared bool) {
|
||||||
|
s.mux.Lock()
|
||||||
|
now := time.Now()
|
||||||
|
if now.Before(s.last.Add(s.wait)) {
|
||||||
|
s.mux.Unlock()
|
||||||
|
return s.result.Val, s.result.Err, true
|
||||||
|
}
|
||||||
|
|
||||||
|
if callM := s.call; callM != nil {
|
||||||
|
s.mux.Unlock()
|
||||||
|
callM.wg.Wait()
|
||||||
|
return callM.val, callM.err, true
|
||||||
|
}
|
||||||
|
|
||||||
|
callM := &call[T]{}
|
||||||
|
callM.wg.Add(1)
|
||||||
|
s.call = callM
|
||||||
|
s.mux.Unlock()
|
||||||
|
callM.val, callM.err = fn()
|
||||||
|
callM.wg.Done()
|
||||||
|
|
||||||
|
s.mux.Lock()
|
||||||
|
s.call = nil
|
||||||
|
s.result = &Result[T]{callM.val, callM.err}
|
||||||
|
s.last = now
|
||||||
|
s.mux.Unlock()
|
||||||
|
return callM.val, callM.err, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Single[T]) Reset() {
|
||||||
|
s.last = time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSingle[T any](wait time.Duration) *Single[T] {
|
||||||
|
return &Single[T]{wait: wait}
|
||||||
|
}
|
69
common/singledo/singledo_test.go
Normal file
69
common/singledo/singledo_test.go
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
package singledo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBasic(t *testing.T) {
|
||||||
|
single := NewSingle[int](time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
shardCount := atomic.NewInt32(0)
|
||||||
|
call := func() (int, error) {
|
||||||
|
foo++
|
||||||
|
time.Sleep(time.Millisecond * 5)
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
const n = 5
|
||||||
|
wg.Add(n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
go func() {
|
||||||
|
_, _, shard := single.Do(call)
|
||||||
|
if shard {
|
||||||
|
shardCount.Inc()
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
assert.Equal(t, 1, foo)
|
||||||
|
assert.Equal(t, int32(4), shardCount.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTimer(t *testing.T) {
|
||||||
|
single := NewSingle[int](time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
callM := func() (int, error) {
|
||||||
|
foo++
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _, _ = single.Do(callM)
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
_, _, shard := single.Do(callM)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, foo)
|
||||||
|
assert.True(t, shard)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReset(t *testing.T) {
|
||||||
|
single := NewSingle[int](time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
callM := func() (int, error) {
|
||||||
|
foo++
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _, _ = single.Do(callM)
|
||||||
|
single.Reset()
|
||||||
|
_, _, _ = single.Do(callM)
|
||||||
|
|
||||||
|
assert.Equal(t, 2, foo)
|
||||||
|
}
|
148
common/snifer/tls/sniff.go
Normal file
148
common/snifer/tls/sniff.go
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
package tls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrNoClue = errors.New("not enough information for making a decision")
|
||||||
|
|
||||||
|
type SniffHeader struct {
|
||||||
|
domain string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SniffHeader) Protocol() string {
|
||||||
|
return "tls"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SniffHeader) Domain() string {
|
||||||
|
return h.domain
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
errNotTLS = errors.New("not TLS header")
|
||||||
|
errNotClientHello = errors.New("not client hello")
|
||||||
|
)
|
||||||
|
|
||||||
|
func IsValidTLSVersion(major, minor byte) bool {
|
||||||
|
return major == 3
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadClientHello returns server name (if any) from TLS client hello message.
|
||||||
|
// https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300
|
||||||
|
func ReadClientHello(data []byte, h *SniffHeader) error {
|
||||||
|
if len(data) < 42 {
|
||||||
|
return ErrNoClue
|
||||||
|
}
|
||||||
|
sessionIDLen := int(data[38])
|
||||||
|
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
|
||||||
|
return ErrNoClue
|
||||||
|
}
|
||||||
|
data = data[39+sessionIDLen:]
|
||||||
|
if len(data) < 2 {
|
||||||
|
return ErrNoClue
|
||||||
|
}
|
||||||
|
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
|
||||||
|
// they are uint16s, the number must be even.
|
||||||
|
cipherSuiteLen := int(data[0])<<8 | int(data[1])
|
||||||
|
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
data = data[2+cipherSuiteLen:]
|
||||||
|
if len(data) < 1 {
|
||||||
|
return ErrNoClue
|
||||||
|
}
|
||||||
|
compressionMethodsLen := int(data[0])
|
||||||
|
if len(data) < 1+compressionMethodsLen {
|
||||||
|
return ErrNoClue
|
||||||
|
}
|
||||||
|
data = data[1+compressionMethodsLen:]
|
||||||
|
|
||||||
|
if len(data) == 0 {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
if len(data) < 2 {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
|
||||||
|
extensionsLength := int(data[0])<<8 | int(data[1])
|
||||||
|
data = data[2:]
|
||||||
|
if extensionsLength != len(data) {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
|
||||||
|
for len(data) != 0 {
|
||||||
|
if len(data) < 4 {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
extension := uint16(data[0])<<8 | uint16(data[1])
|
||||||
|
length := int(data[2])<<8 | int(data[3])
|
||||||
|
data = data[4:]
|
||||||
|
if len(data) < length {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
|
||||||
|
if extension == 0x00 { /* extensionServerName */
|
||||||
|
d := data[:length]
|
||||||
|
if len(d) < 2 {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
namesLen := int(d[0])<<8 | int(d[1])
|
||||||
|
d = d[2:]
|
||||||
|
if len(d) != namesLen {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
for len(d) > 0 {
|
||||||
|
if len(d) < 3 {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
nameType := d[0]
|
||||||
|
nameLen := int(d[1])<<8 | int(d[2])
|
||||||
|
d = d[3:]
|
||||||
|
if len(d) < nameLen {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
if nameType == 0 {
|
||||||
|
serverName := string(d[:nameLen])
|
||||||
|
// An SNI value may not include a
|
||||||
|
// trailing dot. See
|
||||||
|
// https://tools.ietf.org/html/rfc6066#section-3.
|
||||||
|
if strings.HasSuffix(serverName, ".") {
|
||||||
|
return errNotClientHello
|
||||||
|
}
|
||||||
|
h.domain = serverName
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
d = d[nameLen:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data = data[length:]
|
||||||
|
}
|
||||||
|
|
||||||
|
return errNotTLS
|
||||||
|
}
|
||||||
|
|
||||||
|
func SniffTLS(b []byte) (*SniffHeader, error) {
|
||||||
|
if len(b) < 5 {
|
||||||
|
return nil, ErrNoClue
|
||||||
|
}
|
||||||
|
|
||||||
|
if b[0] != 0x16 /* TLS Handshake */ {
|
||||||
|
return nil, errNotTLS
|
||||||
|
}
|
||||||
|
if !IsValidTLSVersion(b[1], b[2]) {
|
||||||
|
return nil, errNotTLS
|
||||||
|
}
|
||||||
|
headerLen := int(binary.BigEndian.Uint16(b[3:5]))
|
||||||
|
if 5+headerLen > len(b) {
|
||||||
|
return nil, ErrNoClue
|
||||||
|
}
|
||||||
|
|
||||||
|
h := &SniffHeader{}
|
||||||
|
err := ReadClientHello(b[5:5+headerLen], h)
|
||||||
|
if err == nil {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
159
common/snifer/tls/sniff_test.go
Normal file
159
common/snifer/tls/sniff_test.go
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
package tls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTLSHeaders(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
input []byte
|
||||||
|
domain string
|
||||||
|
err bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
input: []byte{
|
||||||
|
0x16, 0x03, 0x01, 0x00, 0xc8, 0x01, 0x00, 0x00,
|
||||||
|
0xc4, 0x03, 0x03, 0x1a, 0xac, 0xb2, 0xa8, 0xfe,
|
||||||
|
0xb4, 0x96, 0x04, 0x5b, 0xca, 0xf7, 0xc1, 0xf4,
|
||||||
|
0x2e, 0x53, 0x24, 0x6e, 0x34, 0x0c, 0x58, 0x36,
|
||||||
|
0x71, 0x97, 0x59, 0xe9, 0x41, 0x66, 0xe2, 0x43,
|
||||||
|
0xa0, 0x13, 0xb6, 0x00, 0x00, 0x20, 0x1a, 0x1a,
|
||||||
|
0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30,
|
||||||
|
0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0x14, 0xcc, 0x13,
|
||||||
|
0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d,
|
||||||
|
0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
|
||||||
|
0x00, 0x7b, 0xba, 0xba, 0x00, 0x00, 0xff, 0x01,
|
||||||
|
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00,
|
||||||
|
0x14, 0x00, 0x00, 0x11, 0x63, 0x2e, 0x73, 0x2d,
|
||||||
|
0x6d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66,
|
||||||
|
0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x00, 0x17, 0x00,
|
||||||
|
0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00,
|
||||||
|
0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04,
|
||||||
|
0x01, 0x05, 0x03, 0x08, 0x05, 0x05, 0x01, 0x08,
|
||||||
|
0x06, 0x06, 0x01, 0x02, 0x01, 0x00, 0x05, 0x00,
|
||||||
|
0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
|
||||||
|
0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x0c,
|
||||||
|
0x02, 0x68, 0x32, 0x08, 0x68, 0x74, 0x74, 0x70,
|
||||||
|
0x2f, 0x31, 0x2e, 0x31, 0x00, 0x0b, 0x00, 0x02,
|
||||||
|
0x01, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08,
|
||||||
|
0xaa, 0xaa, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18,
|
||||||
|
0xaa, 0xaa, 0x00, 0x01, 0x00,
|
||||||
|
},
|
||||||
|
domain: "c.s-microsoft.com",
|
||||||
|
err: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte{
|
||||||
|
0x16, 0x03, 0x01, 0x00, 0xee, 0x01, 0x00, 0x00,
|
||||||
|
0xea, 0x03, 0x03, 0xe7, 0x91, 0x9e, 0x93, 0xca,
|
||||||
|
0x78, 0x1b, 0x3c, 0xe0, 0x65, 0x25, 0x58, 0xb5,
|
||||||
|
0x93, 0xe1, 0x0f, 0x85, 0xec, 0x9a, 0x66, 0x8e,
|
||||||
|
0x61, 0x82, 0x88, 0xc8, 0xfc, 0xae, 0x1e, 0xca,
|
||||||
|
0xd7, 0xa5, 0x63, 0x20, 0xbd, 0x1c, 0x00, 0x00,
|
||||||
|
0x8b, 0xee, 0x09, 0xe3, 0x47, 0x6a, 0x0e, 0x74,
|
||||||
|
0xb0, 0xbc, 0xa3, 0x02, 0xa7, 0x35, 0xe8, 0x85,
|
||||||
|
0x70, 0x7c, 0x7a, 0xf0, 0x00, 0xdf, 0x4a, 0xea,
|
||||||
|
0x87, 0x01, 0x14, 0x91, 0x00, 0x20, 0xea, 0xea,
|
||||||
|
0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30,
|
||||||
|
0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0x14, 0xcc, 0x13,
|
||||||
|
0xc0, 0x13, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d,
|
||||||
|
0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
|
||||||
|
0x00, 0x81, 0x9a, 0x9a, 0x00, 0x00, 0xff, 0x01,
|
||||||
|
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00,
|
||||||
|
0x16, 0x00, 0x00, 0x13, 0x77, 0x77, 0x77, 0x30,
|
||||||
|
0x37, 0x2e, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x74,
|
||||||
|
0x61, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x00,
|
||||||
|
0x17, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
|
||||||
|
0x0d, 0x00, 0x14, 0x00, 0x12, 0x04, 0x03, 0x08,
|
||||||
|
0x04, 0x04, 0x01, 0x05, 0x03, 0x08, 0x05, 0x05,
|
||||||
|
0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x00,
|
||||||
|
0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e,
|
||||||
|
0x00, 0x0c, 0x02, 0x68, 0x32, 0x08, 0x68, 0x74,
|
||||||
|
0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31, 0x75, 0x50,
|
||||||
|
0x00, 0x00, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00,
|
||||||
|
0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x9a, 0x9a,
|
||||||
|
0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x8a, 0x8a,
|
||||||
|
0x00, 0x01, 0x00,
|
||||||
|
},
|
||||||
|
domain: "www07.clicktale.net",
|
||||||
|
err: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte{
|
||||||
|
0x16, 0x03, 0x01, 0x00, 0xe6, 0x01, 0x00, 0x00, 0xe2, 0x03, 0x03, 0x81, 0x47, 0xc1,
|
||||||
|
0x66, 0xd5, 0x1b, 0xfa, 0x4b, 0xb5, 0xe0, 0x2a, 0xe1, 0xa7, 0x87, 0x13, 0x1d, 0x11, 0xaa, 0xc6,
|
||||||
|
0xce, 0xfc, 0x7f, 0xab, 0x94, 0xc8, 0x62, 0xad, 0xc8, 0xab, 0x0c, 0xdd, 0xcb, 0x20, 0x6f, 0x9d,
|
||||||
|
0x07, 0xf1, 0x95, 0x3e, 0x99, 0xd8, 0xf3, 0x6d, 0x97, 0xee, 0x19, 0x0b, 0x06, 0x1b, 0xf4, 0x84,
|
||||||
|
0x0b, 0xb6, 0x8f, 0xcc, 0xde, 0xe2, 0xd0, 0x2d, 0x6b, 0x0c, 0x1f, 0x52, 0x53, 0x13, 0x00, 0x08,
|
||||||
|
0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0x00, 0xff, 0x01, 0x00, 0x00, 0x91, 0x00, 0x00, 0x00, 0x0c,
|
||||||
|
0x00, 0x0a, 0x00, 0x00, 0x07, 0x64, 0x6f, 0x67, 0x66, 0x69, 0x73, 0x68, 0x00, 0x0b, 0x00, 0x04,
|
||||||
|
0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x1e,
|
||||||
|
0x00, 0x19, 0x00, 0x18, 0x00, 0x23, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00,
|
||||||
|
0x00, 0x0d, 0x00, 0x1e, 0x00, 0x1c, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 0x07, 0x08, 0x08,
|
||||||
|
0x08, 0x09, 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01,
|
||||||
|
0x06, 0x01, 0x00, 0x2b, 0x00, 0x07, 0x06, 0x7f, 0x1c, 0x7f, 0x1b, 0x7f, 0x1a, 0x00, 0x2d, 0x00,
|
||||||
|
0x02, 0x01, 0x01, 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x2f, 0x35, 0x0c,
|
||||||
|
0xb6, 0x90, 0x0a, 0xb7, 0xd5, 0xc4, 0x1b, 0x2f, 0x60, 0xaa, 0x56, 0x7b, 0x3f, 0x71, 0xc8, 0x01,
|
||||||
|
0x7e, 0x86, 0xd3, 0xb7, 0x0c, 0x29, 0x1a, 0x9e, 0x5b, 0x38, 0x3f, 0x01, 0x72,
|
||||||
|
},
|
||||||
|
domain: "dogfish",
|
||||||
|
err: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte{
|
||||||
|
0x16, 0x03, 0x01, 0x01, 0x03, 0x01, 0x00, 0x00,
|
||||||
|
0xff, 0x03, 0x03, 0x3d, 0x89, 0x52, 0x9e, 0xee,
|
||||||
|
0xbe, 0x17, 0x63, 0x75, 0xef, 0x29, 0xbd, 0x14,
|
||||||
|
0x6a, 0x49, 0xe0, 0x2c, 0x37, 0x57, 0x71, 0x62,
|
||||||
|
0x82, 0x44, 0x94, 0x8f, 0x6e, 0x94, 0x08, 0x45,
|
||||||
|
0x7f, 0xdb, 0xc1, 0x00, 0x00, 0x3e, 0xc0, 0x2c,
|
||||||
|
0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8,
|
||||||
|
0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f, 0x00, 0x9e,
|
||||||
|
0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23,
|
||||||
|
0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, 0x14,
|
||||||
|
0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33,
|
||||||
|
0x00, 0x9d, 0x00, 0x9c, 0x13, 0x02, 0x13, 0x03,
|
||||||
|
0x13, 0x01, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35,
|
||||||
|
0x00, 0x2f, 0x00, 0xff, 0x01, 0x00, 0x00, 0x98,
|
||||||
|
0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00,
|
||||||
|
0x0b, 0x31, 0x30, 0x2e, 0x34, 0x32, 0x2e, 0x30,
|
||||||
|
0x2e, 0x32, 0x34, 0x33, 0x00, 0x0b, 0x00, 0x04,
|
||||||
|
0x03, 0x00, 0x01, 0x02, 0x00, 0x0a, 0x00, 0x0a,
|
||||||
|
0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19,
|
||||||
|
0x00, 0x18, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d,
|
||||||
|
0x00, 0x20, 0x00, 0x1e, 0x04, 0x03, 0x05, 0x03,
|
||||||
|
0x06, 0x03, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06,
|
||||||
|
0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x03,
|
||||||
|
0x02, 0x01, 0x02, 0x02, 0x04, 0x02, 0x05, 0x02,
|
||||||
|
0x06, 0x02, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17,
|
||||||
|
0x00, 0x00, 0x00, 0x2b, 0x00, 0x09, 0x08, 0x7f,
|
||||||
|
0x14, 0x03, 0x03, 0x03, 0x02, 0x03, 0x01, 0x00,
|
||||||
|
0x2d, 0x00, 0x03, 0x02, 0x01, 0x00, 0x00, 0x28,
|
||||||
|
0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
|
||||||
|
0x13, 0x7c, 0x6e, 0x97, 0xc4, 0xfd, 0x09, 0x2e,
|
||||||
|
0x70, 0x2f, 0x73, 0x5a, 0x9b, 0x57, 0x4d, 0x5f,
|
||||||
|
0x2b, 0x73, 0x2c, 0xa5, 0x4a, 0x98, 0x40, 0x3d,
|
||||||
|
0x75, 0x6e, 0xb4, 0x76, 0xf9, 0x48, 0x8f, 0x36,
|
||||||
|
},
|
||||||
|
domain: "10.42.0.243",
|
||||||
|
err: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range cases {
|
||||||
|
header, err := SniffTLS(test.input)
|
||||||
|
if test.err {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("Exepct error but nil in test %v", test)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
|
||||||
|
}
|
||||||
|
if header.Domain() != test.domain {
|
||||||
|
t.Error("expect domain ", test.domain, " but got ", header.Domain())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
19
common/sockopt/reuseaddr_linux.go
Normal file
19
common/sockopt/reuseaddr_linux.go
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package sockopt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func UDPReuseaddr(c *net.UDPConn) (err error) {
|
||||||
|
rc, err := c.SyscallConn()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rc.Control(func(fd uintptr) {
|
||||||
|
err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
11
common/sockopt/reuseaddr_other.go
Normal file
11
common/sockopt/reuseaddr_other.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !linux
|
||||||
|
|
||||||
|
package sockopt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
func UDPReuseaddr(c *net.UDPConn) (err error) {
|
||||||
|
return
|
||||||
|
}
|
@ -28,8 +28,8 @@ func NewDecoder(option Option) *Decoder {
|
|||||||
return &Decoder{option: &option}
|
return &Decoder{option: &option}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode transform a map[string]interface{} to a struct
|
// Decode transform a map[string]any to a struct
|
||||||
func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) 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")
|
||||||
}
|
}
|
||||||
@ -37,14 +37,16 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
v := reflect.ValueOf(dst).Elem()
|
v := reflect.ValueOf(dst).Elem()
|
||||||
for idx := 0; idx < v.NumField(); idx++ {
|
for idx := 0; idx < v.NumField(); idx++ {
|
||||||
field := t.Field(idx)
|
field := t.Field(idx)
|
||||||
|
if field.Anonymous {
|
||||||
|
if err := d.decodeStruct(field.Name, src, v.Field(idx)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
tag := field.Tag.Get(d.option.TagName)
|
tag := field.Tag.Get(d.option.TagName)
|
||||||
str := strings.SplitN(tag, ",", 2)
|
key, omitKey, found := strings.Cut(tag, ",")
|
||||||
key := str[0]
|
omitempty := found && omitKey == "omitempty"
|
||||||
omitempty := false
|
|
||||||
if len(str) > 1 {
|
|
||||||
omitempty = str[1] == "omitempty"
|
|
||||||
}
|
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok || value == nil {
|
if !ok || value == nil {
|
||||||
@ -62,7 +64,7 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
switch val.Kind() {
|
switch val.Kind() {
|
||||||
case reflect.Int:
|
case reflect.Int:
|
||||||
return d.decodeInt(name, data, val)
|
return d.decodeInt(name, data, val)
|
||||||
@ -76,17 +78,21 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error
|
|||||||
return d.decodeMap(name, data, val)
|
return d.decodeMap(name, data, val)
|
||||||
case reflect.Interface:
|
case reflect.Interface:
|
||||||
return d.setInterface(name, data, val)
|
return d.setInterface(name, data, val)
|
||||||
|
case reflect.Struct:
|
||||||
|
return d.decodeStruct(name, data, val)
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("type %s not support", val.Kind().String())
|
return fmt.Errorf("type %s not support", val.Kind().String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.Int:
|
case kind == reflect.Int:
|
||||||
val.SetInt(dataVal.Int())
|
val.SetInt(dataVal.Int())
|
||||||
|
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
|
||||||
|
val.SetInt(int64(dataVal.Float()))
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
var i int64
|
var i int64
|
||||||
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
||||||
@ -104,7 +110,7 @@ func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (e
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
@ -121,7 +127,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
@ -138,7 +144,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
||||||
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
@ -153,9 +159,19 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
for valSlice.Len() <= i {
|
for valSlice.Len() <= i {
|
||||||
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
||||||
}
|
}
|
||||||
currentField := valSlice.Index(i)
|
|
||||||
|
|
||||||
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
||||||
|
if currentData == nil {
|
||||||
|
// in weakly type mode, null will convert to zero value
|
||||||
|
if d.option.WeaklyTypedInput {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// in non-weakly type mode, null will convert to nil if element's zero value is nil, otherwise return an error
|
||||||
|
if elemKind := valElemType.Kind(); elemKind == reflect.Map || elemKind == reflect.Slice {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("'%s' can not be null", fieldName)
|
||||||
|
}
|
||||||
|
currentField := valSlice.Index(i)
|
||||||
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -165,7 +181,7 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeMap(name string, data any, val reflect.Value) error {
|
||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valKeyType := valType.Key()
|
valKeyType := valType.Key()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
@ -214,6 +230,11 @@ func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val refle
|
|||||||
}
|
}
|
||||||
|
|
||||||
v := dataVal.MapIndex(k).Interface()
|
v := dataVal.MapIndex(k).Interface()
|
||||||
|
if v == nil {
|
||||||
|
errors = append(errors, fmt.Sprintf("filed %s invalid", fieldName))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
currentVal := reflect.Indirect(reflect.New(valElemType))
|
currentVal := reflect.Indirect(reflect.New(valElemType))
|
||||||
if err := d.decode(fieldName, v, currentVal); err != nil {
|
if err := d.decode(fieldName, v, currentVal); err != nil {
|
||||||
errors = append(errors, err.Error())
|
errors = append(errors, err.Error())
|
||||||
@ -232,7 +253,160 @@ func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val refle
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) setInterface(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeStruct(name string, data any, val reflect.Value) error {
|
||||||
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
|
||||||
|
// If the type of the value to write to and the data match directly,
|
||||||
|
// then we just set it directly instead of recursing into the structure.
|
||||||
|
if dataVal.Type() == val.Type() {
|
||||||
|
val.Set(dataVal)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
dataValKind := dataVal.Kind()
|
||||||
|
switch dataValKind {
|
||||||
|
case reflect.Map:
|
||||||
|
return d.decodeStructFromMap(name, dataVal, val)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error {
|
||||||
|
dataValType := dataVal.Type()
|
||||||
|
if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"'%s' needs a map with string keys, has '%s' keys",
|
||||||
|
name, dataValType.Key().Kind())
|
||||||
|
}
|
||||||
|
|
||||||
|
dataValKeys := make(map[reflect.Value]struct{})
|
||||||
|
dataValKeysUnused := make(map[any]struct{})
|
||||||
|
for _, dataValKey := range dataVal.MapKeys() {
|
||||||
|
dataValKeys[dataValKey] = struct{}{}
|
||||||
|
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
errors := make([]string, 0)
|
||||||
|
|
||||||
|
// This slice will keep track of all the structs we'll be decoding.
|
||||||
|
// There can be more than one struct if there are embedded structs
|
||||||
|
// that are squashed.
|
||||||
|
structs := make([]reflect.Value, 1, 5)
|
||||||
|
structs[0] = val
|
||||||
|
|
||||||
|
// Compile the list of all the fields that we're going to be decoding
|
||||||
|
// from all the structs.
|
||||||
|
type field struct {
|
||||||
|
field reflect.StructField
|
||||||
|
val reflect.Value
|
||||||
|
}
|
||||||
|
fields := []field{}
|
||||||
|
for len(structs) > 0 {
|
||||||
|
structVal := structs[0]
|
||||||
|
structs = structs[1:]
|
||||||
|
|
||||||
|
structType := structVal.Type()
|
||||||
|
|
||||||
|
for i := 0; i < structType.NumField(); i++ {
|
||||||
|
fieldType := structType.Field(i)
|
||||||
|
fieldKind := fieldType.Type.Kind()
|
||||||
|
|
||||||
|
// If "squash" is specified in the tag, we squash the field down.
|
||||||
|
squash := false
|
||||||
|
tagParts := strings.Split(fieldType.Tag.Get(d.option.TagName), ",")
|
||||||
|
for _, tag := range tagParts[1:] {
|
||||||
|
if tag == "squash" {
|
||||||
|
squash = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if squash {
|
||||||
|
if fieldKind != reflect.Struct {
|
||||||
|
errors = append(errors,
|
||||||
|
fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind).Error())
|
||||||
|
} else {
|
||||||
|
structs = append(structs, structVal.FieldByName(fieldType.Name))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal struct field, store it away
|
||||||
|
fields = append(fields, field{fieldType, structVal.Field(i)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// for fieldType, field := range fields {
|
||||||
|
for _, f := range fields {
|
||||||
|
field, fieldValue := f.field, f.val
|
||||||
|
fieldName := field.Name
|
||||||
|
|
||||||
|
tagValue := field.Tag.Get(d.option.TagName)
|
||||||
|
tagValue = strings.SplitN(tagValue, ",", 2)[0]
|
||||||
|
if tagValue != "" {
|
||||||
|
fieldName = tagValue
|
||||||
|
}
|
||||||
|
|
||||||
|
rawMapKey := reflect.ValueOf(fieldName)
|
||||||
|
rawMapVal := dataVal.MapIndex(rawMapKey)
|
||||||
|
if !rawMapVal.IsValid() {
|
||||||
|
// Do a slower search by iterating over each key and
|
||||||
|
// doing case-insensitive search.
|
||||||
|
for dataValKey := range dataValKeys {
|
||||||
|
mK, ok := dataValKey.Interface().(string)
|
||||||
|
if !ok {
|
||||||
|
// Not a string key
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.EqualFold(mK, fieldName) {
|
||||||
|
rawMapKey = dataValKey
|
||||||
|
rawMapVal = dataVal.MapIndex(dataValKey)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !rawMapVal.IsValid() {
|
||||||
|
// There was no matching key in the map for the value in
|
||||||
|
// the struct. Just ignore.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the key we're using from the unused map so we stop tracking
|
||||||
|
delete(dataValKeysUnused, rawMapKey.Interface())
|
||||||
|
|
||||||
|
if !fieldValue.IsValid() {
|
||||||
|
// This should never happen
|
||||||
|
panic("field is not valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we can't set the field, then it is unexported or something,
|
||||||
|
// and we just continue onwards.
|
||||||
|
if !fieldValue.CanSet() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the name is empty string, then we're at the root, and we
|
||||||
|
// don't dot-join the fields.
|
||||||
|
if name != "" {
|
||||||
|
fieldName = fmt.Sprintf("%s.%s", name, fieldName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errors) > 0 {
|
||||||
|
return fmt.Errorf(strings.Join(errors, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) setInterface(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
val.Set(dataVal)
|
val.Set(dataVal)
|
||||||
return nil
|
return nil
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user