Compare commits
581 Commits
plus
...
dev-refact
Author | SHA1 | Date | |
---|---|---|---|
637a8b6ed5 | |||
cd466f05d3 | |||
9a55213ddc | |||
5055542d61 | |||
23063ae0b9 | |||
a7f9aa909a | |||
15ecc451f3 | |||
186a4cfdf3 | |||
220ef9e2e2 | |||
7079116aa8 | |||
b9e6de45e6 | |||
d3503ff940 | |||
c3f4e1ba2e | |||
695fb64fa8 | |||
d32ab9ce74 | |||
94648989b8 | |||
07522d3c2e | |||
c14c07d2e3 | |||
9511ccfe47 | |||
ed17a1bf23 | |||
2a4f2f3942 | |||
3254eaf51c | |||
7941bae141 | |||
35a6666a84 | |||
73d5042774 | |||
9126cbab91 | |||
f8366f6e42 | |||
100c9b94ba | |||
8343c3597e | |||
d31adafa11 | |||
1acc6759e9 | |||
e995003c27 | |||
9edee2435c | |||
5d337b75f9 | |||
2188fad9c1 | |||
edc73f3f33 | |||
ade424cbb4 | |||
6e03773134 | |||
4ad0294655 | |||
43d3a0c8ea | |||
c045a4f2a7 | |||
20611eb8dc | |||
8ff7e180a4 | |||
3827e00b54 | |||
c52e689d0d | |||
cb517cb529 | |||
50bb620aa1 | |||
c745ea63b2 | |||
8e959bd245 | |||
298ca42369 | |||
ed9b9ce3c5 | |||
1298d2f8b6 | |||
6e84f685ce | |||
1ad87cfec9 | |||
9e9f459c0e | |||
fa3e0c726e | |||
3b038310ab | |||
6709936a8f | |||
04e5d02ab9 | |||
1af39cb228 | |||
c95735f083 | |||
fa2e6be05d | |||
4092a7c84b | |||
58d299c737 | |||
11ddac2b5f | |||
1f95c74f1e | |||
a197fbd4b5 | |||
708b8beadf | |||
0e1601e5b6 | |||
c7355510a2 | |||
1faa172944 | |||
7a8c98cd90 | |||
13e907bbd0 | |||
39e7832676 | |||
9b999e72ce | |||
e1a61503e4 | |||
9272d02149 | |||
067c02aba1 | |||
d0268bb9a2 | |||
fb4872ff7f | |||
2044458df9 | |||
d6df026550 | |||
7858ca6cc5 | |||
ac36473d13 | |||
72fb153fe0 | |||
527a602eba | |||
a71fd3b4df | |||
2ebc0383b5 | |||
7431001ed6 | |||
149b4b5b43 | |||
c0eb9aac1c | |||
79469fc8d6 | |||
948700eed6 | |||
3ab82849d4 | |||
0f43a19fdb | |||
cc1c1340a3 | |||
fe25ae83df | |||
c787bbe0e5 | |||
7aff9aac82 | |||
8b09db5f7f | |||
b5623602f5 | |||
16b27b3a1f | |||
8b00be9039 | |||
fa9e27c5e4 | |||
f4d9384603 | |||
c4408612b3 | |||
0742f7db26 | |||
891c2fe899 | |||
b831eb178b | |||
962ceaa89e | |||
d52b00bd34 | |||
aa0d174ccb | |||
b8e9c3d55a | |||
0b4c498c93 | |||
efc7c82cac | |||
63917aa020 | |||
5016f529af | |||
5bd5f1bfda | |||
d4dcbce9cb | |||
df8196a68c | |||
c1631759fc | |||
9e9c3c810f | |||
463101aec1 | |||
2072964701 | |||
aded1b78b5 | |||
ca9c859059 | |||
55811dae32 | |||
7136d145f8 | |||
2fbbf7519f | |||
663bf4fbb0 | |||
f0a22a4a4c | |||
4ab91520bd | |||
980d8a2641 | |||
a95d439852 | |||
a08e39faec | |||
b3295262c1 | |||
27aa026568 | |||
9969e1706e | |||
fb58595d44 | |||
bdfa16ca6f | |||
b307bcb4a9 | |||
f26941091b | |||
6cd5769ed7 | |||
41adfa65b3 | |||
3fbb7c7a2d | |||
0aa82c04ea | |||
5c6f2694c7 | |||
eca7615f08 | |||
52d559bb38 | |||
259736390a | |||
7db07630a7 | |||
d617b0f447 | |||
80ff5917f7 | |||
b401da5eba | |||
05b25c334f | |||
2c5a47a275 | |||
b2605a9012 | |||
b929a19f48 | |||
4b04faa88b | |||
5fee0b5bf1 | |||
27120fb0f5 | |||
0cf539fb82 | |||
26a38bd8de | |||
ebbce4d061 | |||
5acd2f6c3a | |||
fe2bc903b8 | |||
658f1f5cda | |||
5ccc047fe4 | |||
6d704b9cd1 | |||
5f957b5cf9 | |||
8681728b8d | |||
bb1eb5979b | |||
032b6a2cc5 | |||
45a02e3439 | |||
9d8cd036ff | |||
2aad9818e8 | |||
4d5c0d2bf4 | |||
861205dbbe | |||
9dbe20f2c5 | |||
8dea62cd63 | |||
2d99f86780 | |||
fac63625fc | |||
b9f270162a | |||
bbbe371ea9 | |||
e2409f9639 | |||
4f634edaa9 | |||
f1dab9e9ce | |||
8217db82ce | |||
f9dd0a6bfc | |||
b9b25be68d | |||
179e5aad58 | |||
fc1eaf9a9d | |||
1756730693 | |||
c7bc67e44c | |||
949c1551f8 | |||
b23a333acf | |||
47568051bf | |||
22c1e05e1c | |||
c161d5e6be | |||
573be855f7 | |||
a38b2bcb6d | |||
2e74986fe4 | |||
30eaa8add6 | |||
b498d2dda2 | |||
96a32f5038 | |||
e11f6f84df | |||
5a1e1050b7 | |||
73aa8c7be7 | |||
183973e823 | |||
2e08a4b4e1 | |||
564a6fdf35 | |||
cca3a1a934 | |||
ffb49ba4c5 | |||
e4fb10faf9 | |||
16a35527b7 | |||
4fd7d0f707 | |||
dee1aeb6c3 | |||
2f95d56a12 | |||
c77993eed3 | |||
ce663a7b96 | |||
9c2ca0feb0 | |||
b8d5321615 | |||
eb6f7e3158 | |||
0947cb4a5a | |||
0368bb4180 | |||
4aeac0e227 | |||
bd3c493c9f | |||
0a99fc4d74 | |||
19fc70b2c4 | |||
81b5543b0d | |||
2e1d9a4f2e | |||
de4341c8cd | |||
8a85c63b08 | |||
b0dd74e74e | |||
4dd9e199b7 | |||
3d6aea4c1e | |||
0cb5270452 | |||
3f6d2e5f91 | |||
3b16fcef92 | |||
f91d106cdf | |||
9e6ba64940 | |||
bee1bddceb | |||
e98dcc4267 | |||
4b79f8de93 | |||
f40c2eb71d | |||
7ca1a03d73 | |||
6c4791480e | |||
42d853a7e6 | |||
5d36d8b139 | |||
5a4441c47f | |||
0ca10798ea | |||
3ea3653d7a | |||
58cd8f9ac1 | |||
ea0d236259 | |||
48a01adb7a | |||
f8d7f29856 | |||
1cf9321aa0 | |||
71a1f5dfbd | |||
25426cba33 | |||
9d364f66e9 | |||
7c23fa2bd4 | |||
0658ecadd3 | |||
efbc334b3b | |||
80764217c2 | |||
45fe6e996b | |||
36a719e2f8 | |||
1b6b0052c2 | |||
c981ef0f28 | |||
1bf291d240 | |||
b179d09efb | |||
4be17653e0 | |||
21446ba5d4 | |||
75ce6b59bf | |||
ce96ac35fb | |||
173e10abe6 | |||
a6eb11ce18 | |||
0c65f6962a | |||
baa9e02af6 | |||
673541e2a8 | |||
14878b37f6 | |||
83e0abaa8c | |||
7166db2ac9 | |||
815a060309 | |||
544e0f137d | |||
07906c0aa5 | |||
b2981f921c | |||
7be3e617ab | |||
9a3bc8ef9e | |||
e083d1c57d | |||
ce4902e5e6 | |||
4b9edc3b66 | |||
91e48b707b | |||
5719b9d22f | |||
b553dd749b | |||
9461bcd44e | |||
6548dc90fa | |||
908ca20afa | |||
88e4b3575e | |||
559b3ff9f3 | |||
127634028d | |||
81c5a65f23 | |||
591ee119c2 | |||
5b03cc56e7 | |||
c4216218c8 | |||
63840b3358 | |||
045dd0589b | |||
705311b70e | |||
55ce40fbd1 | |||
07fda93111 | |||
012e044c54 | |||
b323315583 | |||
4c10d6e212 | |||
ece3bb360a | |||
5a7b9bdf45 | |||
028ecb70c5 | |||
4e0b22f42d | |||
dbd27ef910 | |||
ffff1418f2 | |||
64a5fd02da | |||
611ce5f5f1 | |||
0a0b8074f4 | |||
f66c3b6f86 | |||
a3d49d1ed4 | |||
0d068e7b5f | |||
24583009c4 | |||
a593d68c42 | |||
520657e953 | |||
6c64164bee | |||
9b4ddbed2c | |||
79d984ee8e | |||
7a54d616c4 | |||
f19b67fe9d | |||
91e83ea955 | |||
a375b85fa0 | |||
4cc661920e | |||
b5f6f26de4 | |||
e068563b58 | |||
bf6839e5f3 | |||
e0040b7e5d | |||
3beb71b6e1 | |||
668d29d91f | |||
5386c3903d | |||
6a4d2b3368 | |||
d9d8507c8f | |||
5b7f46bc97 | |||
d1838f663e | |||
2d1c031ce0 | |||
e67f94b87a | |||
2df890c4ee | |||
520256365e | |||
9270d3c475 | |||
c8b1050c15 | |||
39de5d58c8 | |||
a38f30ec3b | |||
2ea92d70f9 | |||
ea2e715da9 | |||
1350330fe0 | |||
317797acc8 | |||
8766764d49 | |||
b8d48e1618 | |||
f972d1fa58 | |||
df78ba8fa6 | |||
0c83575302 | |||
e9151bc43f | |||
68345b6a19 | |||
435bee0ca2 | |||
92d169ca81 | |||
30f1b29257 | |||
c503e44324 | |||
ce509295c0 | |||
f671d6a1fd | |||
e194efcecb | |||
609d69191a | |||
c791044ddf | |||
dc2abe6eeb | |||
1071e3f4a3 | |||
acc249495d | |||
5a2cc9a36f | |||
1cc6cfab9c | |||
0183d752a0 | |||
2f24e49ff6 | |||
016862f7a5 | |||
c3df768f79 | |||
0f2123179a | |||
1034780e8e | |||
f01ac69654 | |||
c85305ead8 | |||
3e89bee524 | |||
68fccfacc0 | |||
cf52fbed65 | |||
a924819fbf | |||
13c82754ff | |||
002163f07b | |||
9c5b184db6 | |||
3ab784dd80 | |||
f1c4d85eb3 | |||
b9fc393f95 | |||
557347d366 | |||
a7f3b85200 | |||
7550067fde | |||
076a0840bf | |||
5ebcc526de | |||
3772ad8ddb | |||
5ad7237fa7 | |||
49e25f502f | |||
06942c67fd | |||
9259c9f3ff | |||
37cf166d14 | |||
27292dac0c | |||
847c91503b | |||
ca8ed0a01b | |||
46dc262e8e | |||
7465eaafa1 | |||
d70cfefde7 | |||
52c37f7140 | |||
180bce2940 | |||
4a446c4e31 | |||
d7f5e8d3de | |||
0a180eeb40 | |||
7ff48ea42d | |||
a0e44f4041 | |||
2f6f9ebc2e | |||
28a1475f66 | |||
c28f42d823 | |||
2bf34c766e | |||
35b19c3d7f | |||
90e6ed4612 | |||
ae5a790510 | |||
3b277aa8ec | |||
176eb3926b | |||
776728fb30 | |||
a732e1a603 | |||
1cdaf782ba | |||
f1157d0a09 | |||
f376409041 | |||
45b3afdd33 | |||
875fdb3a5b | |||
25e115d042 | |||
d633e3d96e | |||
6e9d837a7d | |||
63b9d66365 | |||
be0fadc09e | |||
76dccebbf6 | |||
cd5b735973 | |||
9e4e1482d9 | |||
9974fba56e | |||
4bd5764c4e | |||
deeab8b45f | |||
af30664c51 | |||
6962f0b7e1 | |||
6e5859d1bf | |||
87ca93b979 | |||
11052d8f77 | |||
a5ce62db33 | |||
2f8e575308 | |||
62b70725ef | |||
8595d6c2e9 | |||
03b956b7a3 | |||
e5c99cbee7 | |||
58a47e1835 | |||
daf83eb6f7 | |||
bb68b59c9a | |||
c3cfa3d6cd | |||
b15344ec78 | |||
56c38890f9 | |||
daae846db3 | |||
ee6c1871a9 | |||
00e44cd141 | |||
4ab986cccb | |||
64869d0f17 | |||
7f0368da66 | |||
4f1b227ca2 | |||
16abba385a | |||
75b5f633cd | |||
8ae68552a6 | |||
d35d6c9ac9 | |||
a832cfdb65 | |||
951a5a0eb5 | |||
89609cc4a2 | |||
bfb976bbdc | |||
a15d2535f1 | |||
610c79570a | |||
051c81518c | |||
0209efd423 | |||
ba6fdd2962 | |||
c14dd79e69 | |||
9475799615 | |||
14917c8af1 | |||
3bb32d12e0 | |||
013b839678 | |||
a06382cebc | |||
ebc3f36236 | |||
e2a0437685 | |||
82c8e02d02 | |||
a210ec4197 | |||
0b72395704 | |||
8955107d6b | |||
69aef9cec0 | |||
9e44e21406 | |||
b0fdd8dc47 | |||
e92ef587bb | |||
5657aa50cf | |||
7d17d53a8f | |||
58ef4ddbba | |||
a78b89d16e | |||
833b43a538 | |||
8df3efe932 | |||
645c3154d6 | |||
a847d7b58d | |||
37ea8aff5c | |||
cb4ce8be6a | |||
a85395e777 | |||
819b29956b | |||
eb999b3bf1 | |||
8580ee8898 | |||
58552447ef | |||
23ca356447 | |||
fae65b97ec | |||
99f0231a9b | |||
edf1bb476d | |||
5c53243e81 | |||
b99b4ad15f | |||
6369921364 | |||
c6f923041f | |||
53eb3f15bb | |||
b15a7c8b6f | |||
038f973f90 | |||
bf6bfdd930 | |||
0431969a73 | |||
c7b257b188 | |||
885f69b81d | |||
cb52682790 | |||
c65835d9e4 | |||
92bb026f70 | |||
c22c7efd07 | |||
e4b30dacd4 | |||
353ae30839 | |||
828ff82ff2 | |||
35cf39e415 | |||
340efef2d8 | |||
796eb5c95c | |||
0f2b87497b | |||
06e9243fda | |||
d4cc650633 | |||
14af94205c | |||
078389f4f6 | |||
cad18b7529 | |||
aeddc8eb1d | |||
f7393509a3 | |||
8e641a4e31 | |||
223de1f3fd | |||
1fb2bc07d7 | |||
eb57d246cf | |||
0001a1b844 | |||
b20e202321 | |||
900e852525 | |||
1f3968bd50 | |||
5d510eb5aa | |||
3d246d5150 | |||
3686446919 | |||
a412745314 | |||
d0c23998d2 | |||
038cc1f6b5 | |||
6bd186d3c0 | |||
4c6bb7178b | |||
cec14db4a8 | |||
53287d597b | |||
964bbe1957 | |||
c824ace2d7 | |||
78cef7df59 | |||
62b3ebe49f | |||
ff420ed2ee | |||
d1568325e6 | |||
5a27df899f | |||
ab12b440aa | |||
4b614090f8 | |||
63d07db4bf | |||
cbea46b0c8 | |||
c0e9d69163 | |||
d29d824da8 | |||
862174d21b |
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,76 +0,0 @@
|
||||
name: Bug report
|
||||
description: Create a report to help us improve
|
||||
title: "[Bug] "
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: ensure
|
||||
attributes:
|
||||
label: Verify steps
|
||||
description: "
|
||||
在提交之前,请确认
|
||||
Please verify that you've followed these steps
|
||||
"
|
||||
options:
|
||||
- label: "
|
||||
如果你可以自己 debug 并解决的话,提交 PR 吧
|
||||
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
||||
"
|
||||
required: true
|
||||
- label: "
|
||||
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
||||
I have searched on the [issue tracker](……/) for a related issue.
|
||||
"
|
||||
required: true
|
||||
- label: "
|
||||
我已经使用 dev 分支版本测试过,问题依旧存在
|
||||
I have tested using the dev branch, and the issue still exists.
|
||||
"
|
||||
required: true
|
||||
- label: "
|
||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
||||
"
|
||||
required: true
|
||||
- label: "
|
||||
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
||||
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
||||
"
|
||||
required: true
|
||||
- type: input
|
||||
attributes:
|
||||
label: Clash version
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: os
|
||||
attributes:
|
||||
label: What OS are you seeing the problem on?
|
||||
multiple: true
|
||||
options:
|
||||
- macOS
|
||||
- Windows
|
||||
- Linux
|
||||
- OpenBSD/FreeBSD
|
||||
- type: textarea
|
||||
attributes:
|
||||
render: yaml
|
||||
label: "Clash config"
|
||||
description: "
|
||||
在下方附上 Clash core 脱敏后配置文件的内容
|
||||
Paste the Clash core configuration below.
|
||||
"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
render: shell
|
||||
label: Clash log
|
||||
description: "
|
||||
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
||||
"
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Description
|
||||
validations:
|
||||
required: true
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
6
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -1,6 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
|
||||
contact_links:
|
||||
- name: Get help in GitHub Discussions
|
||||
url: https://github.com/Dreamacro/clash/discussions
|
||||
about: Have a question? Not sure if your issue affects everyone reproducibly? The quickest way to get help is on Clash's GitHub Discussions!
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,36 +0,0 @@
|
||||
name: Feature request
|
||||
description: Suggest an idea for this project
|
||||
title: "[Feature] "
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: ensure
|
||||
attributes:
|
||||
label: Verify steps
|
||||
description: "
|
||||
在提交之前,请确认
|
||||
Please verify that you've followed these steps
|
||||
"
|
||||
options:
|
||||
- label: "
|
||||
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
||||
I have searched on the [issue tracker](……/) for a related feature request.
|
||||
"
|
||||
required: true
|
||||
- label: "
|
||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
||||
"
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Description
|
||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Possible Solution
|
||||
description: "
|
||||
此项非必须,但是如果你有想法的话欢迎提出。
|
||||
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
||||
"
|
75
.github/workflows/build-windows-amd.yml
vendored
75
.github/workflows/build-windows-amd.yml
vendored
@ -1,75 +0,0 @@
|
||||
name: Build-Windows
|
||||
on: [push]
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.18.x
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Go cache paths
|
||||
id: go-cache-paths
|
||||
run: |
|
||||
echo "::set-output name=go-build::$(go env GOCACHE)"
|
||||
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
||||
|
||||
- name: Cache go module
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: |
|
||||
${{ steps.go-cache-paths.outputs.go-mod }}
|
||||
${{ steps.go-cache-paths.outputs.go-build }}
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v3
|
||||
with:
|
||||
python-version: '3.9'
|
||||
architecture: 'x64'
|
||||
|
||||
- name: Get dependencies, run test
|
||||
id: test
|
||||
run: |
|
||||
cmd /c mklink /J D:\python-amd64 $env:pythonLocation
|
||||
|
||||
echo "::set-output name=file_sha::$(git describe --tags --always)"
|
||||
echo "::set-output name=file_date::$(Get-Date -Format 'yyyyMMdd')"
|
||||
|
||||
((Get-Content -path constant/version.go -Raw) -replace 'unknown version',$(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
|
20
.github/workflows/build.yaml
vendored
Normal file
20
.github/workflows/build.yaml
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
name: Build All
|
||||
on:
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v1
|
||||
with:
|
||||
go-version: 1.18
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v1
|
||||
- name: Build
|
||||
run: make all
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: bin/*
|
||||
draft: true
|
29
.github/workflows/codeql-analysis.yml
vendored
29
.github/workflows/codeql-analysis.yml
vendored
@ -1,29 +0,0 @@
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ rm ]
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ['go']
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
61
.github/workflows/docker.yaml
vendored
Normal file
61
.github/workflows/docker.yaml
vendored
Normal file
@ -0,0 +1,61 @@
|
||||
name: Docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- Beta
|
||||
tags:
|
||||
- "v*"
|
||||
env:
|
||||
REGISTRY: docker.io
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
with:
|
||||
version: latest
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v3
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||
|
||||
- name: Log into registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
|
||||
# Build and push Docker image with Buildx (don't push on PR)
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
platforms: |
|
||||
linux/386
|
||||
linux/amd64
|
||||
linux/arm64/v8
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
80
.github/workflows/docker.yml
vendored
80
.github/workflows/docker.yml
vendored
@ -1,80 +0,0 @@
|
||||
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
23
.github/workflows/linter.yml
vendored
@ -1,23 +0,0 @@
|
||||
name: Linter
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Get latest go version
|
||||
id: version
|
||||
run: |
|
||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ steps.version.outputs.go_version }}
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v3
|
||||
with:
|
||||
version: latest
|
||||
args: --build-tags=build_local
|
70
.github/workflows/prerelease.yml
vendored
Normal file
70
.github/workflows/prerelease.yml
vendored
Normal file
@ -0,0 +1,70 @@
|
||||
name: Prerelease
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- Alpha
|
||||
- Beta
|
||||
pull_request:
|
||||
branches:
|
||||
- Alpha
|
||||
- Beta
|
||||
jobs:
|
||||
Build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get latest go version
|
||||
id: version
|
||||
run: |
|
||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ steps.version.outputs.go_version }}
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Cache go module
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
|
||||
- name: Test
|
||||
if: ${{github.ref_name=='Beta'}}
|
||||
run: |
|
||||
go test ./...
|
||||
|
||||
- name: Build
|
||||
if: success()
|
||||
env:
|
||||
NAME: Clash.Meta
|
||||
BINDIR: bin
|
||||
run: make -j$(($(nproc) + 1)) releases
|
||||
|
||||
- name: Delete current release assets
|
||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: Prerelease-${{ github.ref_name }}
|
||||
deleteOnlyFromDrafts: false
|
||||
|
||||
- name: Tag Repo
|
||||
uses: richardsimko/update-tag@v1
|
||||
with:
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload Alpha
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
files: bin/*
|
||||
prerelease: true
|
||||
generate_release_notes: true
|
44
.github/workflows/release.yaml
vendored
Normal file
44
.github/workflows/release.yaml
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
jobs:
|
||||
Build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get latest go version
|
||||
id: version
|
||||
run: |
|
||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ steps.version.outputs.go_version }}
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
- name: Cache go module
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
- name: Test
|
||||
run: |
|
||||
go test ./...
|
||||
- name: Build
|
||||
if: success()
|
||||
env:
|
||||
NAME: Clash.Meta
|
||||
BINDIR: bin
|
||||
run: make -j$(($(nproc) + 1)) releases
|
||||
|
||||
- name: Upload Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
||||
with:
|
||||
tag: ${{ github.ref }}
|
||||
files: bin/*
|
||||
generate_release_notes: true
|
120
.github/workflows/release.yml
vendored
120
.github/workflows/release.yml
vendored
@ -1,120 +0,0 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- rm
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get latest go version
|
||||
id: version
|
||||
run: |
|
||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ steps.version.outputs.go_version }}
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Go cache paths
|
||||
id: go-cache-paths
|
||||
run: |
|
||||
echo "::set-output name=go-build::$(go env GOCACHE)"
|
||||
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
||||
|
||||
- name: Cache go module
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: |
|
||||
${{ steps.go-cache-paths.outputs.go-mod }}
|
||||
${{ steps.go-cache-paths.outputs.go-build }}
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: '3.9'
|
||||
|
||||
- name: Get dependencies, run test
|
||||
run: |
|
||||
# fetch python cross compile source files
|
||||
mkdir -p bin/python/
|
||||
cd bin/python/
|
||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-darwin-amd64.tar.xz
|
||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-darwin-arm64.tar.xz
|
||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-windows-amd64.tar.xz
|
||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-windows-386.tar.xz
|
||||
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-amd64.tar.xz
|
||||
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-arm64.tar.xz
|
||||
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-386.tar.xz
|
||||
tar -Jxf python-3.9.7-darwin-amd64.tar.xz
|
||||
tar -Jxf python-3.9.7-darwin-arm64.tar.xz
|
||||
tar -Jxf python-3.9.7-windows-amd64.tar.xz
|
||||
tar -Jxf python-3.9.7-windows-386.tar.xz
|
||||
#tar -Jxf python-3.9.7-linux-amd64.tar.xz
|
||||
#tar -Jxf python-3.9.7-linux-arm64.tar.xz
|
||||
#tar -Jxf python-3.9.7-linux-386.tar.xz
|
||||
rm python-3.9.7-*.tar.xz
|
||||
cd ../../
|
||||
|
||||
# go test
|
||||
go test -tags build_local ./...
|
||||
|
||||
# init xgo
|
||||
docker pull techknowlogick/xgo:latest
|
||||
go install src.techknowlogick.com/xgo@latest
|
||||
|
||||
- name: Build
|
||||
#if: startsWith(github.ref, 'refs/tags/')
|
||||
env:
|
||||
NAME: clash
|
||||
BINDIR: bin
|
||||
run: |
|
||||
make -j releases
|
||||
#ls -lahF bin/python/
|
||||
|
||||
- name: Prepare upload
|
||||
if: startsWith(github.ref, 'refs/tags/') == false
|
||||
run: |
|
||||
rm -rf bin/python/
|
||||
echo "FILE_DATE=_$(date +"%Y%m%d%H%M")" >> $GITHUB_ENV
|
||||
echo "FILE_SHA=$(git describe --tags --always 2>/dev/null)" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload files to Artifacts
|
||||
uses: actions/upload-artifact@v2
|
||||
if: startsWith(github.ref, 'refs/tags/') == false
|
||||
with:
|
||||
name: clash_${{ env.FILE_SHA }}${{ env.FILE_DATE }}
|
||||
path: |
|
||||
bin/*
|
||||
|
||||
- name: Upload Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: bin/*
|
||||
draft: true
|
||||
prerelease: true
|
||||
generate_release_notes: true
|
||||
|
||||
- name: Delete workflow runs
|
||||
uses: GitRML/delete-workflow-runs@main
|
||||
with:
|
||||
retain_days: 1
|
||||
keep_minimum_runs: 2
|
||||
|
||||
- name: Remove old Releases
|
||||
uses: dev-drprasad/delete-older-releases@v0.2.0
|
||||
if: startsWith(github.ref, 'refs/tags/') && !cancelled()
|
||||
with:
|
||||
keep_latest: 1
|
||||
delete_tags: true
|
||||
delete_tag_pattern: plus-pro
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
19
.github/workflows/stale.yml
vendored
19
.github/workflows/stale.yml
vendored
@ -1,19 +0,0 @@
|
||||
|
||||
name: Mark stale issues and pull requests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- rm
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/stale@v5
|
||||
with:
|
||||
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
|
||||
days-before-stale: 60
|
||||
days-before-close: 5
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -23,3 +23,5 @@ vendor
|
||||
|
||||
# test suite
|
||||
test/config/cache*
|
||||
/output
|
||||
/.vscode
|
28
Dockerfile
28
Dockerfile
@ -1,18 +1,26 @@
|
||||
FROM golang:alpine as builder
|
||||
|
||||
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
|
||||
COPY --from=tonistiigi/xx:golang / /
|
||||
mkdir /clash-config && \
|
||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||
|
||||
|
||||
COPY . /clash-src
|
||||
RUN go mod download && \
|
||||
make docker && \
|
||||
mv ./bin/clash-docker /clash
|
||||
WORKDIR /clash-src
|
||||
RUN go mod download &&\
|
||||
make docker &&\
|
||||
mv ./bin/Clash.Meta-docker /clash
|
||||
|
||||
FROM alpine:latest
|
||||
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata
|
||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||
COPY --from=builder /clash /
|
||||
ENTRYPOINT ["/clash"]
|
||||
|
||||
VOLUME ["/root/.config/clash/"]
|
||||
|
||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||
COPY --from=builder /clash /clash
|
||||
RUN chmod +x /clash
|
||||
ENTRYPOINT [ "/clash" ]
|
156
Makefile
156
Makefile
@ -1,70 +1,129 @@
|
||||
GOCMD=go
|
||||
XGOCMD=xgo -go=go-1.18.x
|
||||
GOBUILD=CGO_ENABLED=1 $(GOCMD) build -trimpath
|
||||
GOCLEAN=$(GOCMD) clean
|
||||
NAME=clash
|
||||
BINDIR=$(shell pwd)/bin
|
||||
VERSION=$(shell git describe --tags --always 2>/dev/null || date +%F)
|
||||
NAME=Clash.Meta
|
||||
BINDIR=bin
|
||||
BRANCH=$(shell git branch --show-current)
|
||||
ifeq ($(BRANCH),Alpha)
|
||||
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
||||
else ifeq ($(BRANCH),Beta)
|
||||
VERSION=beta-$(shell git rev-parse --short HEAD)
|
||||
else ifeq ($(BRANCH),)
|
||||
VERSION=$(shell git describe --tags)
|
||||
else
|
||||
VERSION=$(shell git rev-parse --short HEAD)
|
||||
endif
|
||||
|
||||
BUILDTIME=$(shell date -u)
|
||||
BUILD_PACKAGE=.
|
||||
RELEASE_LDFLAGS='-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||
-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='
|
||||
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||
-w -s -buildid='
|
||||
|
||||
PLATFORM_LIST = \
|
||||
darwin-amd64 \
|
||||
darwin-arm64 \
|
||||
linux-amd64
|
||||
# linux-arm64
|
||||
# linux-386
|
||||
linux-amd64-compatible \
|
||||
linux-amd64 \
|
||||
linux-armv5 \
|
||||
linux-armv6 \
|
||||
linux-armv7 \
|
||||
linux-arm64 \
|
||||
linux-mips64 \
|
||||
linux-mips64le \
|
||||
linux-mips-softfloat \
|
||||
linux-mips-hardfloat \
|
||||
linux-mipsle-softfloat \
|
||||
linux-mipsle-hardfloat \
|
||||
android-arm64 \
|
||||
freebsd-386 \
|
||||
freebsd-amd64 \
|
||||
freebsd-arm64
|
||||
|
||||
WINDOWS_ARCH_LIST = \
|
||||
windows-386 \
|
||||
windows-amd64-compatible \
|
||||
windows-amd64 \
|
||||
windows-386
|
||||
# windows-arm64
|
||||
windows-arm64 \
|
||||
windows-arm32v7
|
||||
|
||||
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||
all:linux-amd64 linux-arm64\
|
||||
darwin-amd64 darwin-arm64\
|
||||
windows-amd64 windows-arm64\
|
||||
|
||||
local:
|
||||
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
local-v3:
|
||||
GOAMD64=v3 $(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
||||
docker:
|
||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
darwin-amd64:
|
||||
$(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
|
||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
darwin-amd64-compatible:
|
||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
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
|
||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-386:
|
||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/386 $(BUILD_PACKAGE)
|
||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-amd64:
|
||||
$(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)
|
||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-amd64-compatible:
|
||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-arm64:
|
||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/arm64 $(BUILD_PACKAGE)
|
||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-armv5:
|
||||
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-armv6:
|
||||
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-armv7:
|
||||
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-mips-softfloat:
|
||||
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-mips-hardfloat:
|
||||
GOARCH=mips GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-mipsle-softfloat:
|
||||
GOARCH=mipsle GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-mipsle-hardfloat:
|
||||
GOARCH=mipsle GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-mips64:
|
||||
GOARCH=mips64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
linux-mips64le:
|
||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
android-arm64:
|
||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
freebsd-386:
|
||||
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
freebsd-amd64:
|
||||
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
freebsd-arm64:
|
||||
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
windows-386:
|
||||
$(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
|
||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
|
||||
windows-amd64:
|
||||
$(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
|
||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.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
|
||||
windows-amd64-compatible:
|
||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
|
||||
windows-arm64:
|
||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
|
||||
windows-arm32v7:
|
||||
GOARCH=arm GOOS=windows GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
|
||||
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
||||
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
||||
@ -81,17 +140,10 @@ all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
||||
releases: $(gz_releases) $(zip_releases)
|
||||
|
||||
vet:
|
||||
$(GOCMD) test -tags build_local ./...
|
||||
go test ./...
|
||||
|
||||
lint:
|
||||
golangci-lint run --build-tags=build_local ./...
|
||||
golangci-lint run ./...
|
||||
|
||||
clean:
|
||||
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)
|
||||
rm $(BINDIR)/*
|
||||
|
418
README.md
418
README.md
@ -1,23 +1,20 @@
|
||||
<h1 align="center">
|
||||
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
||||
<br>Clash<br>
|
||||
<img src="Meta.png" alt="Meta Kennel" width="200">
|
||||
<br>Meta Kernel<br>
|
||||
</h1>
|
||||
|
||||
<h4 align="center">A rule-based tunnel in Go.</h4>
|
||||
<h3 align="center">Another Clash Kernel.</h3>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Dreamacro/clash/actions">
|
||||
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
||||
</a>
|
||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
||||
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
||||
</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">
|
||||
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
||||
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
||||
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
||||
</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 href="https://github.com/Clash-Mini/Clash.Meta">
|
||||
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@ -36,145 +33,85 @@
|
||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||
|
||||
## Advanced usage for this branch
|
||||
### Build
|
||||
This branch requires cgo and Python3.9, so make sure you set up Python3.9 before building.
|
||||
|
||||
For example, build on macOS:
|
||||
```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
|
||||
```
|
||||
|
||||
### MITM configuration
|
||||
A root CA certificate is required, the
|
||||
MITM proxy server will generate a CA certificate file and a CA private key file in your Clash home directory, you can use your own certificate replace it.
|
||||
|
||||
Need to install and trust the CA certificate on the client device, open this URL [http://mitm.clash/cert.crt](http://mitm.clash/cert.crt) by the web browser to install the CA certificate, the host name 'mitm.clash' was always been hijacked.
|
||||
|
||||
NOTE: this feature cannot work on tls pinning
|
||||
|
||||
WARNING: DO NOT USE THIS FEATURE TO BREAK LOCAL LAWS
|
||||
|
||||
```yaml
|
||||
# Port of MITM proxy server on the local end
|
||||
mitm-port: 7894
|
||||
|
||||
# Man-In-The-Middle attack
|
||||
mitm:
|
||||
hosts: # use for others proxy type. E.g: TUN, socks
|
||||
- +.example.com
|
||||
rules: # rewrite rules
|
||||
- '^https?://www\.example\.com/1 url reject' # The "reject" returns HTTP status code 404 with no content.
|
||||
- '^https?://www\.example\.com/2 url reject-200' # The "reject-200" returns HTTP status code 200 with no content.
|
||||
- '^https?://www\.example\.com/3 url reject-img' # The "reject-img" returns HTTP status code 200 with content of 1px png.
|
||||
- '^https?://www\.example\.com/4 url reject-dict' # The "reject-dict" returns HTTP status code 200 with content of empty json object.
|
||||
- '^https?://www\.example\.com/5 url reject-array' # The "reject-array" returns HTTP status code 200 with content of empty json array.
|
||||
- '^https?://www\.example\.com/(6) url 302 https://www.example.com/new-$1'
|
||||
- '^https?://www\.(example)\.com/7 url 307 https://www.$1.com/new-7'
|
||||
- '^https?://www\.example\.com/8 url request-header (\r\n)User-Agent:.+(\r\n) request-header $1User-Agent: haha-wriohoh$2' # The "request-header" works for all the http headers not just one single header, so you can match two or more headers including CRLF in one regular expression.
|
||||
- '^https?://www\.example\.com/9 url request-body "pos_2":\[.*\],"pos_3" request-body "pos_2":[{"xx": "xx"}],"pos_3"'
|
||||
- '^https?://www\.example\.com/10 url response-header (\r\n)Tracecode:.+(\r\n) response-header $1Tracecode: 88888888888$2'
|
||||
- '^https?://www\.example\.com/11 url response-body "errmsg":"ok" response-body "errmsg":"not-ok"'
|
||||
```
|
||||
|
||||
### DNS configuration
|
||||
Support resolve ip with a proxy tunnel.
|
||||
|
||||
Support `geosite` with `fallback-filter`.
|
||||
|
||||
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
|
||||
```
|
||||
Restore `Redir remote resolution`.
|
||||
|
||||
Support resolve ip with a `Proxy Tunnel`.
|
||||
|
||||
```yaml
|
||||
proxy-groups:
|
||||
|
||||
- name: DNS
|
||||
type: url-test
|
||||
use:
|
||||
- HK
|
||||
url: http://cp.cloudflare.com
|
||||
interval: 180
|
||||
lazy: true
|
||||
```
|
||||
```yaml
|
||||
dns:
|
||||
enable: true
|
||||
use-hosts: true
|
||||
ipv6: false
|
||||
enhanced-mode: redir-host
|
||||
fake-ip-range: 198.18.0.1/16
|
||||
listen: 127.0.0.1:6868
|
||||
default-nameserver:
|
||||
- 119.29.29.29
|
||||
- 114.114.114.114
|
||||
nameserver:
|
||||
- https://doh.pub/dns-query
|
||||
- tls://223.5.5.5:853
|
||||
fallback:
|
||||
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
||||
- 'tls://8.8.4.4:853#DNS'
|
||||
fallback-filter:
|
||||
geoip: false
|
||||
geosite:
|
||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
||||
domain:
|
||||
- +.example.com
|
||||
ipcidr:
|
||||
- 0.0.0.0/32
|
||||
```
|
||||
|
||||
### TUN configuration
|
||||
|
||||
Supports macOS, Linux and Windows.
|
||||
|
||||
On Windows, you should download the [Wintun](https://www.wintun.net) driver and copy `wintun.dll` into the system32 directory.
|
||||
Built-in [Wintun](https://www.wintun.net) driver.
|
||||
|
||||
```yaml
|
||||
# Enable the TUN listener
|
||||
tun:
|
||||
enable: true
|
||||
stack: gvisor # System or gVisor
|
||||
# device: tun://utun8 # or fd://xxx, it's optional
|
||||
stack: gvisor # only gvisor
|
||||
dns-hijack:
|
||||
- 0.0.0.0:53 # hijack all public
|
||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||
auto-route: true # auto set global route
|
||||
```
|
||||
### Rules configuration
|
||||
- Support rule `GEOSITE`.
|
||||
- Support rule `USER-AGENT`.
|
||||
- Support rule-providers `RULE-SET`.
|
||||
- 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).
|
||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-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(tcp/udp) condition for all rules
|
||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||
|
||||
# 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
|
||||
@ -185,134 +122,94 @@ rules:
|
||||
- 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
|
||||
|
||||
- GEOIP,telegram,PROXY,no-resolve
|
||||
- GEOIP,private,DIRECT,no-resolve
|
||||
- GEOIP,cn,DIRECT
|
||||
|
||||
- MATCH,PROXY
|
||||
```
|
||||
|
||||
### Script configuration
|
||||
Script enables users to programmatically select a policy for the packets with more flexibility.
|
||||
|
||||
```yaml
|
||||
mode: script
|
||||
|
||||
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"
|
||||
|
||||
if metadata["network"] == 'udp' and metadata["dst_port"] == 443:
|
||||
return "REJECT"
|
||||
|
||||
host = metadata["host"]
|
||||
for kw in ['analytics', 'adservice', 'firebase', 'bugly', 'safebrowsing', 'doubleclick']:
|
||||
if kw in host:
|
||||
return "REJECT"
|
||||
|
||||
now = time.now()
|
||||
if (now.hour < 8 or now.hour > 17) and metadata["src_ip"] == '192.168.1.99':
|
||||
return "REJECT"
|
||||
|
||||
if ctx.rule_providers["geosite:category-ads-all"].match(metadata):
|
||||
return "REJECT"
|
||||
|
||||
if ctx.rule_providers["geosite:youtube"].match(metadata):
|
||||
ctx.log('[Script] domain %s matched youtube' % host)
|
||||
return "Proxy"
|
||||
|
||||
if ctx.rule_providers["geosite:geolocation-cn"].match(metadata):
|
||||
ctx.log('[Script] domain %s matched geolocation-cn' % host)
|
||||
return "DIRECT"
|
||||
|
||||
ip = metadata["dst_ip"]
|
||||
if host != "":
|
||||
ip = ctx.resolve_ip(host)
|
||||
if ip == "":
|
||||
return "Proxy"
|
||||
|
||||
code = ctx.geoip(ip)
|
||||
if code == "LAN" or code == "CN":
|
||||
return "DIRECT"
|
||||
|
||||
return "Proxy" # default policy for requests which are not matched by any other script
|
||||
```
|
||||
the context and metadata
|
||||
```ts
|
||||
interface Metadata {
|
||||
type: string // socks5、http
|
||||
network: string // tcp
|
||||
host: string
|
||||
process_name: string
|
||||
process_path: string
|
||||
src_ip: string
|
||||
src_port: int
|
||||
dst_ip: string
|
||||
dst_port: int
|
||||
}
|
||||
|
||||
interface Context {
|
||||
resolve_ip: (host: string) => string // ip string
|
||||
geoip: (ip: string) => string // country code
|
||||
log: (log: string) => void
|
||||
rule_providers: Record<string, { match: (metadata: Metadata) => boolean }>
|
||||
}
|
||||
```
|
||||
|
||||
### Proxies configuration
|
||||
Support outbound protocol `VLESS`.
|
||||
|
||||
Support `Trojan` with XTLS.
|
||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
||||
|
||||
Currently XTLS only supports TCP transport.
|
||||
Support `Policy Group Filter`
|
||||
|
||||
```yaml
|
||||
proxy-groups:
|
||||
|
||||
- name: 🚀 HK Group
|
||||
type: select
|
||||
use:
|
||||
- ALL
|
||||
filter: 'HK'
|
||||
|
||||
- name: 🚀 US Group
|
||||
type: select
|
||||
use:
|
||||
- ALL
|
||||
filter: 'US'
|
||||
|
||||
proxy-providers:
|
||||
ALL:
|
||||
type: http
|
||||
url: "xxxxx"
|
||||
interval: 3600
|
||||
path: "xxxxx"
|
||||
health-check:
|
||||
enable: true
|
||||
interval: 600
|
||||
url: http://www.gstatic.com/generate_204
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
Support outbound transport protocol `VLESS`.
|
||||
|
||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||
```yaml
|
||||
proxies:
|
||||
# VLESS
|
||||
- name: "vless-tls"
|
||||
- name: "vless"
|
||||
type: vless
|
||||
server: server
|
||||
port: 443
|
||||
uuid: uuid
|
||||
network: tcp
|
||||
servername: example.com
|
||||
servername: example.com # AKA SNI
|
||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
||||
# skip-cert-verify: true
|
||||
|
||||
- name: "vless-ws"
|
||||
type: vless
|
||||
server: server
|
||||
port: 443
|
||||
uuid: uuid
|
||||
tls: true
|
||||
udp: true
|
||||
network: ws
|
||||
servername: example.com # priority over wss host
|
||||
# skip-cert-verify: true
|
||||
- name: "vless-xtls"
|
||||
ws-opts:
|
||||
path: /path
|
||||
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
||||
|
||||
- name: "vless-grpc"
|
||||
type: vless
|
||||
server: server
|
||||
port: 443
|
||||
uuid: uuid
|
||||
network: tcp
|
||||
servername: example.com
|
||||
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||
# flow-show: true # print the XTLS direction log
|
||||
# udp: true
|
||||
# skip-cert-verify: true
|
||||
|
||||
# Trojan
|
||||
- name: "trojan-xtls"
|
||||
type: trojan
|
||||
server: server
|
||||
port: 443
|
||||
password: yourpsk
|
||||
network: tcp
|
||||
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||
# flow-show: true # print the XTLS direction log
|
||||
# udp: true
|
||||
# sni: example.com # aka server name
|
||||
tls: true
|
||||
udp: true
|
||||
network: grpc
|
||||
servername: example.com # priority over wss host
|
||||
# skip-cert-verify: true
|
||||
grpc-opts:
|
||||
grpc-service-name: grpcname
|
||||
```
|
||||
|
||||
### IPTABLES configuration
|
||||
@ -326,60 +223,73 @@ iptables:
|
||||
enable: true # default is false
|
||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||
```
|
||||
Run Clash as a daemon.
|
||||
|
||||
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
||||
```shell
|
||||
|
||||
### General installation guide for Linux
|
||||
+ Create user given name `clash-meta`
|
||||
|
||||
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||
|
||||
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||
|
||||
+ Create folder `/etc/Clash-Meta/` as working directory
|
||||
|
||||
|
||||
|
||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||
|
||||
Create the systemd configuration file at `/etc/systemd/system/Clash-Meta.service`:
|
||||
|
||||
```
|
||||
[Unit]
|
||||
Description=Clash daemon, A rule-based proxy in Go.
|
||||
After=network.target
|
||||
Description=Clash-Meta Daemon, Another Clash Kernel.
|
||||
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=clash-meta
|
||||
Group=clash-meta
|
||||
LimitNPROC=500
|
||||
LimitNOFILE=1000000
|
||||
CapabilityBoundingSet=cap_net_admin
|
||||
AmbientCapabilities=cap_net_admin
|
||||
Restart=always
|
||||
ExecStart=/usr/local/bin/clash -d /etc/clash
|
||||
ExecStartPre=/usr/bin/sleep 1s
|
||||
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
Launch clashd on system startup with:
|
||||
```shell
|
||||
$ systemctl enable clash
|
||||
$ systemctl enable Clash-Meta
|
||||
```
|
||||
Launch clashd immediately with:
|
||||
|
||||
```shell
|
||||
$ systemctl start clash
|
||||
$ systemctl start Clash-Meta
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||
|
||||
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.
|
||||
To display process name in GUI please use [Dashboard For Meta](https://github.com/Clash-Mini/Dashboard).
|
||||
|
||||
## 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)
|
||||
|
||||
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
|
||||
|
||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||
* [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)
|
||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||
|
||||
## License
|
||||
|
||||
|
@ -3,24 +3,21 @@ package adapter
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"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
|
||||
var UnifiedDelay = atomic.NewBool(false)
|
||||
|
||||
type Proxy struct {
|
||||
C.ProxyAdapter
|
||||
@ -43,7 +40,11 @@ func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
||||
// 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))
|
||||
wasCancel := false
|
||||
if err != nil {
|
||||
wasCancel = strings.Contains(err.Error(), "operation was canceled")
|
||||
}
|
||||
p.alive.Store(err == nil || wasCancel)
|
||||
return conn, err
|
||||
}
|
||||
|
||||
@ -116,6 +117,8 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||
}
|
||||
}()
|
||||
|
||||
unifiedDelay := UnifiedDelay.Load()
|
||||
|
||||
addr, err := urlToMetadata(url)
|
||||
if err != nil {
|
||||
return
|
||||
@ -154,11 +157,18 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||
},
|
||||
}
|
||||
defer client.CloseIdleConnections()
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if unifiedDelay {
|
||||
start = time.Now()
|
||||
resp, err = client.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
t = uint16(time.Since(start) / time.Millisecond)
|
||||
return
|
||||
|
@ -11,7 +11,7 @@ import (
|
||||
// NewHTTPS receive CONNECT request and return ConnContext
|
||||
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
||||
metadata := parseHTTPAddr(request)
|
||||
metadata.Type = C.HTTPCONNECT
|
||||
metadata.Type = C.HTTPS
|
||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
|
@ -1,22 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/context"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
)
|
||||
|
||||
// NewMitm receive mitm request and return MitmContext
|
||||
func NewMitm(target socks5.Addr, source net.Addr, userAgent string, conn net.Conn) *context.ConnContext {
|
||||
metadata := parseSocksAddr(target)
|
||||
metadata.NetWork = C.TCP
|
||||
metadata.Type = C.MITM
|
||||
metadata.UserAgent = userAgent
|
||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
return context.NewConnContext(conn, metadata)
|
||||
}
|
@ -2,7 +2,7 @@ package inbound
|
||||
|
||||
import (
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
||||
@ -17,8 +17,8 @@ func (s *PacketAdapter) Metadata() *C.Metadata {
|
||||
}
|
||||
|
||||
// NewPacket is PacketAdapter generator
|
||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||
metadata := parseSocksAddr(target)
|
||||
func NewPacket(target M.Socksaddr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||
metadata := socksAddrToMetadata(target)
|
||||
metadata.NetWork = C.UDP
|
||||
metadata.Type = source
|
||||
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||
|
@ -2,6 +2,7 @@ package inbound
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/context"
|
||||
@ -13,9 +14,37 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
||||
metadata := parseSocksAddr(target)
|
||||
metadata.NetWork = C.TCP
|
||||
metadata.Type = source
|
||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
remoteAddr := conn.RemoteAddr()
|
||||
// Filter when net.Addr interface is nil
|
||||
if remoteAddr != nil {
|
||||
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
}
|
||||
|
||||
return context.NewConnContext(conn, metadata)
|
||||
}
|
||||
|
||||
func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
||||
metadata := &C.Metadata{}
|
||||
metadata.NetWork = C.TCP
|
||||
metadata.Type = C.INNER
|
||||
metadata.DNSMode = C.DNSMapping
|
||||
metadata.Host = host
|
||||
metadata.AddrType = C.AtypDomainName
|
||||
metadata.Process = C.ClashName
|
||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||
metadata.DstPort = port
|
||||
if host == "" {
|
||||
if ip, err := netip.ParseAddr(h); err == nil {
|
||||
metadata.DstIP = ip
|
||||
metadata.AddrType = C.AtypIPv4
|
||||
if ip.Is6() {
|
||||
metadata.AddrType = C.AtypIPv6
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return context.NewConnContext(conn, metadata)
|
||||
|
@ -10,8 +10,26 @@ import (
|
||||
"github.com/Dreamacro/clash/common/nnip"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
func socksAddrToMetadata(addr M.Socksaddr) *C.Metadata {
|
||||
metadata := &C.Metadata{}
|
||||
switch addr.Family() {
|
||||
case M.AddressFamilyIPv4:
|
||||
metadata.AddrType = C.AtypIPv4
|
||||
metadata.DstIP = addr.Addr
|
||||
case M.AddressFamilyIPv6:
|
||||
metadata.AddrType = C.AtypIPv6
|
||||
metadata.DstIP = addr.Addr
|
||||
case M.AddressFamilyFqdn:
|
||||
metadata.AddrType = C.AtypDomainName
|
||||
metadata.Host = addr.Fqdn
|
||||
}
|
||||
metadata.DstPort = strconv.Itoa(int(addr.Port))
|
||||
return metadata
|
||||
}
|
||||
|
||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||
metadata := &C.Metadata{
|
||||
AddrType: int(target[0]),
|
||||
|
@ -5,9 +5,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/gofrs/uuid"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
@ -17,6 +23,7 @@ type Base struct {
|
||||
tp C.AdapterType
|
||||
udp bool
|
||||
rmark int
|
||||
id string
|
||||
}
|
||||
|
||||
// Name implements C.ProxyAdapter
|
||||
@ -24,6 +31,20 @@ func (b *Base) Name() string {
|
||||
return b.name
|
||||
}
|
||||
|
||||
// Id implements C.ProxyAdapter
|
||||
func (b *Base) Id() string {
|
||||
if b.id == "" {
|
||||
id, err := uuid.NewV6()
|
||||
if err != nil {
|
||||
b.id = b.name
|
||||
} else {
|
||||
b.id = id.String()
|
||||
}
|
||||
}
|
||||
|
||||
return b.id
|
||||
}
|
||||
|
||||
// Type implements C.ProxyAdapter
|
||||
func (b *Base) Type() C.AdapterType {
|
||||
return b.tp
|
||||
@ -34,11 +55,25 @@ func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
return c, errors.New("no support")
|
||||
}
|
||||
|
||||
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||
return nil, 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")
|
||||
}
|
||||
|
||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||
func (b *Base) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
return nil, errors.New("no support")
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
func (b *Base) SupportUOT() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// SupportUDP implements C.ProxyAdapter
|
||||
func (b *Base) SupportUDP() bool {
|
||||
return b.udp
|
||||
@ -48,6 +83,7 @@ func (b *Base) SupportUDP() bool {
|
||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(map[string]string{
|
||||
"type": b.Type().String(),
|
||||
"id": b.Id(),
|
||||
})
|
||||
}
|
||||
|
||||
@ -101,7 +137,12 @@ func NewBase(opt BaseOption) *Base {
|
||||
|
||||
type conn struct {
|
||||
net.Conn
|
||||
chain C.Chain
|
||||
chain C.Chain
|
||||
actualRemoteDestination string
|
||||
}
|
||||
|
||||
func (c *conn) RemoteDestination() string {
|
||||
return c.actualRemoteDestination
|
||||
}
|
||||
|
||||
// Chains implements C.Connection
|
||||
@ -115,12 +156,18 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
||||
}
|
||||
|
||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||
return &conn{c, []string{a.Name()}}
|
||||
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||
}
|
||||
|
||||
type packetConn struct {
|
||||
net.PacketConn
|
||||
chain C.Chain
|
||||
nc N.PacketConn
|
||||
chain C.Chain
|
||||
actualRemoteDestination string
|
||||
}
|
||||
|
||||
func (c *packetConn) RemoteDestination() string {
|
||||
return c.actualRemoteDestination
|
||||
}
|
||||
|
||||
// Chains implements C.Connection
|
||||
@ -133,6 +180,32 @@ 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()}}
|
||||
func (c *packetConn) ReadPacket(buffer *buf.Buffer) (addr M.Socksaddr, err error) {
|
||||
return c.nc.ReadPacket(buffer)
|
||||
}
|
||||
|
||||
func (c *packetConn) WritePacket(buffer *buf.Buffer, addr M.Socksaddr) error {
|
||||
return c.nc.WritePacket(buffer, addr)
|
||||
}
|
||||
|
||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||
var nc N.PacketConn
|
||||
if n, isNc := pc.(N.PacketConn); isNc {
|
||||
nc = n
|
||||
} else {
|
||||
nc = &bufio.PacketConnWrapper{PacketConn: pc}
|
||||
}
|
||||
return &packetConn{pc, nc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||
}
|
||||
|
||||
func parseRemoteDestination(addr string) string {
|
||||
if dst, _, err := net.SplitHostPort(addr); err == nil {
|
||||
return dst
|
||||
} else {
|
||||
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
||||
return dst
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -46,3 +46,13 @@ func NewDirect() *Direct {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func NewCompatible() *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: "COMPATIBLE",
|
||||
tp: C.Compatible,
|
||||
udp: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -22,18 +22,20 @@ type Http struct {
|
||||
user string
|
||||
pass string
|
||||
tlsConfig *tls.Config
|
||||
option *HttpOption
|
||||
}
|
||||
|
||||
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"`
|
||||
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"`
|
||||
Headers map[string]string `proxy:"headers,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
@ -84,15 +86,18 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||
},
|
||||
}
|
||||
|
||||
// 增加headers
|
||||
if len(h.option.Headers) != 0 {
|
||||
for key, value := range h.option.Headers {
|
||||
req.Header.Add(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
if h.user != "" && h.pass != "" {
|
||||
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
|
||||
}
|
||||
@ -145,5 +150,6 @@ func NewHttp(option HttpOption) *Http {
|
||||
user: option.UserName,
|
||||
pass: option.Password,
|
||||
tlsConfig: tlsConfig,
|
||||
option: &option,
|
||||
}
|
||||
}
|
||||
|
270
adapter/outbound/hysteria.go
Normal file
270
adapter/outbound/hysteria.go
Normal file
@ -0,0 +1,270 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
"github.com/lucas-clemente/quic-go"
|
||||
"github.com/lucas-clemente/quic-go/congestion"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
hyCongestion "github.com/tobyxdd/hysteria/pkg/congestion"
|
||||
"github.com/tobyxdd/hysteria/pkg/core"
|
||||
"github.com/tobyxdd/hysteria/pkg/obfs"
|
||||
"github.com/tobyxdd/hysteria/pkg/pmtud_fix"
|
||||
"github.com/tobyxdd/hysteria/pkg/transport"
|
||||
)
|
||||
|
||||
const (
|
||||
mbpsToBps = 125000
|
||||
minSpeedBPS = 16384
|
||||
|
||||
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
||||
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||
DefaultMaxIncomingStreams = 1024
|
||||
|
||||
DefaultALPN = "hysteria"
|
||||
DefaultProtocol = "udp"
|
||||
)
|
||||
|
||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||
|
||||
type Hysteria struct {
|
||||
*Base
|
||||
|
||||
client *core.Client
|
||||
clientTransport *transport.ClientTransport
|
||||
}
|
||||
|
||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), hyDialer(func() (net.PacketConn, error) {
|
||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewConn(tcpConn, h), nil
|
||||
}
|
||||
|
||||
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||
udpConn, err := h.client.DialUDP(hyDialer(func() (net.PacketConn, error) {
|
||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||
}
|
||||
|
||||
type HysteriaOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Protocol string `proxy:"protocol,omitempty"`
|
||||
Up string `proxy:"up,omitempty"`
|
||||
UpMbps int `proxy:"up_mbps,omitempty"`
|
||||
Down string `proxy:"down,omitempty"`
|
||||
DownMbps int `proxy:"down_mbps,omitempty"`
|
||||
Auth string `proxy:"auth,omitempty"`
|
||||
AuthString string `proxy:"auth_str,omitempty"`
|
||||
Obfs string `proxy:"obfs,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
ALPN string `proxy:"alpn,omitempty"`
|
||||
CustomCA string `proxy:"ca,omitempty"`
|
||||
CustomCAString string `proxy:"ca_str,omitempty"`
|
||||
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
|
||||
ReceiveWindow int `proxy:"recv_window,omitempty"`
|
||||
DisableMTUDiscovery bool `proxy:"disable_mtu_discovery,omitempty"`
|
||||
}
|
||||
|
||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||
var up, down uint64
|
||||
if len(c.Up) > 0 {
|
||||
up = stringToBps(c.Up)
|
||||
if up == 0 {
|
||||
return 0, 0, errors.New("invalid speed format")
|
||||
}
|
||||
} else {
|
||||
up = uint64(c.UpMbps) * mbpsToBps
|
||||
}
|
||||
if len(c.Down) > 0 {
|
||||
down = stringToBps(c.Down)
|
||||
if down == 0 {
|
||||
return 0, 0, errors.New("invalid speed format")
|
||||
}
|
||||
} else {
|
||||
down = uint64(c.DownMbps) * mbpsToBps
|
||||
}
|
||||
return up, down, nil
|
||||
}
|
||||
|
||||
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||
clientTransport := &transport.ClientTransport{
|
||||
Dialer: &net.Dialer{
|
||||
Timeout: 8 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
serverName := option.Server
|
||||
if option.SNI != "" {
|
||||
serverName = option.Server
|
||||
}
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: serverName,
|
||||
InsecureSkipVerify: option.SkipCertVerify,
|
||||
MinVersion: tls.VersionTLS13,
|
||||
}
|
||||
if len(option.ALPN) > 0 {
|
||||
tlsConfig.NextProtos = []string{option.ALPN}
|
||||
} else {
|
||||
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||
}
|
||||
if len(option.CustomCA) > 0 {
|
||||
bs, err := ioutil.ReadFile(option.CustomCA)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
||||
}
|
||||
cp := x509.NewCertPool()
|
||||
if !cp.AppendCertsFromPEM(bs) {
|
||||
return nil, fmt.Errorf("hysteria %s failed to parse ca_str", addr)
|
||||
}
|
||||
tlsConfig.RootCAs = cp
|
||||
} else if option.CustomCAString != "" {
|
||||
cp := x509.NewCertPool()
|
||||
if !cp.AppendCertsFromPEM([]byte(option.CustomCAString)) {
|
||||
return nil, fmt.Errorf("hysteria %s failed to parse ca_str", addr)
|
||||
}
|
||||
tlsConfig.RootCAs = cp
|
||||
}
|
||||
quicConfig := &quic.Config{
|
||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||
KeepAlive: true,
|
||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||
EnableDatagrams: true,
|
||||
}
|
||||
if option.Protocol == "" {
|
||||
option.Protocol = DefaultProtocol
|
||||
}
|
||||
if option.ReceiveWindowConn == 0 {
|
||||
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||
}
|
||||
if option.ReceiveWindow == 0 {
|
||||
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
||||
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
||||
}
|
||||
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
|
||||
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
|
||||
}
|
||||
var auth []byte
|
||||
if option.Auth != "" {
|
||||
authBytes, err := base64.StdEncoding.DecodeString(option.Auth)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hysteria %s parse auth error: %w", addr, err)
|
||||
}
|
||||
auth = authBytes
|
||||
} else {
|
||||
auth = []byte(option.AuthString)
|
||||
}
|
||||
var obfuscator obfs.Obfuscator
|
||||
if len(option.Obfs) > 0 {
|
||||
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
||||
}
|
||||
up, down, _ := option.Speed()
|
||||
client, err := core.NewClient(
|
||||
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||
}, obfuscator,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||
}
|
||||
return &Hysteria{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
addr: addr,
|
||||
tp: C.Hysteria,
|
||||
udp: true,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
},
|
||||
client: client,
|
||||
clientTransport: clientTransport,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func stringToBps(s string) uint64 {
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
m := rateStringRegexp.FindStringSubmatch(s)
|
||||
if m == nil {
|
||||
return 0
|
||||
}
|
||||
var n uint64
|
||||
switch m[2] {
|
||||
case "K":
|
||||
n = 1 << 10
|
||||
case "M":
|
||||
n = 1 << 20
|
||||
case "G":
|
||||
n = 1 << 30
|
||||
case "T":
|
||||
n = 1 << 40
|
||||
default:
|
||||
n = 1
|
||||
}
|
||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||
n = v * n
|
||||
if m[3] == "b" {
|
||||
// Bits, need to convert to bytes
|
||||
n = n >> 3
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
type hyPacketConn struct {
|
||||
core.UDPConn
|
||||
}
|
||||
|
||||
func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
b, addrStr, err := c.UDPConn.ReadFrom()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n = copy(p, b)
|
||||
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
||||
return
|
||||
}
|
||||
|
||||
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n = len(p)
|
||||
return
|
||||
}
|
||||
|
||||
type hyDialer func() (net.PacketConn, error)
|
||||
|
||||
func (h hyDialer) ListenPacket() (net.PacketConn, error) {
|
||||
return h()
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type Mitm struct {
|
||||
*Base
|
||||
serverAddr *net.TCPAddr
|
||||
httpProxyClient *Http
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
func (m *Mitm) DialContext(_ context.Context, metadata *C.Metadata, _ ...dialer.Option) (C.Conn, error) {
|
||||
c, err := net.DialTCP("tcp", nil, m.serverAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_ = c.SetKeepAlive(true)
|
||||
_ = c.SetKeepAlivePeriod(60 * time.Second)
|
||||
|
||||
metadata.Type = C.MITM
|
||||
|
||||
hc, err := m.httpProxyClient.StreamConn(c, metadata)
|
||||
if err != nil {
|
||||
_ = c.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewConn(hc, m), nil
|
||||
}
|
||||
|
||||
func NewMitm(serverAddr string) *Mitm {
|
||||
tcpAddr, _ := net.ResolveTCPAddr("tcp", serverAddr)
|
||||
return &Mitm{
|
||||
Base: &Base{
|
||||
name: "Mitm",
|
||||
tp: C.Mitm,
|
||||
},
|
||||
serverAddr: tcpAddr,
|
||||
httpProxyClient: NewHttp(HttpOption{}),
|
||||
}
|
||||
}
|
@ -6,43 +6,16 @@ import (
|
||||
"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
|
||||
}
|
||||
|
||||
@ -61,6 +34,16 @@ func NewReject() *Reject {
|
||||
}
|
||||
}
|
||||
|
||||
func NewPass() *Reject {
|
||||
return &Reject{
|
||||
Base: &Base{
|
||||
name: "PASS",
|
||||
tp: C.Pass,
|
||||
udp: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type nopConn struct{}
|
||||
|
||||
func (rw *nopConn) Read(b []byte) (int, error) {
|
||||
|
@ -13,13 +13,15 @@ import (
|
||||
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"
|
||||
"github.com/sagernet/sing-shadowsocks"
|
||||
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
type ShadowSocks struct {
|
||||
*Base
|
||||
cipher core.Cipher
|
||||
method shadowsocks.Method
|
||||
|
||||
// obfs
|
||||
obfsMode string
|
||||
@ -69,9 +71,7 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||
}
|
||||
}
|
||||
c = ss.cipher.StreamConn(c)
|
||||
_, err := c.Write(serializesSocksAddr(metadata))
|
||||
return c, err
|
||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@ -100,16 +100,13 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
||||
pc.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pc = ss.cipher.PacketConn(pc)
|
||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
||||
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
||||
return newPacketConn(pc, 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)
|
||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||
}
|
||||
@ -162,7 +159,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
},
|
||||
cipher: ciph,
|
||||
method: method,
|
||||
|
||||
obfsMode: obfsMode,
|
||||
v2rayOption: v2rayOption,
|
||||
|
@ -8,12 +8,11 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||
"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 {
|
||||
|
@ -53,6 +53,10 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
||||
// 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})
|
||||
if metadata.NetWork == C.UDP {
|
||||
err := snell.WriteUDPHeader(c, s.version)
|
||||
return c, err
|
||||
}
|
||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||
return c, err
|
||||
@ -104,6 +108,17 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
||||
return newPacketConn(pc, s), nil
|
||||
}
|
||||
|
||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
pc := snell.PacketConn(c)
|
||||
return newPacketConn(pc, s), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
func (s *Snell) SupportUOT() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func NewSnell(option SnellOption) (*Snell, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
psk := []byte(option.Psk)
|
||||
|
@ -13,8 +13,6 @@ import (
|
||||
"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 {
|
||||
@ -25,7 +23,7 @@ type Trojan struct {
|
||||
// for gun mux
|
||||
gunTLSConfig *tls.Config
|
||||
gunConfig *gun.Config
|
||||
transport *http2.Transport
|
||||
transport *gun.TransportWrap
|
||||
}
|
||||
|
||||
type TrojanOption struct {
|
||||
@ -90,6 +88,10 @@ func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if metadata.NetWork == C.UDP {
|
||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||
return c, err
|
||||
}
|
||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||
return c, err
|
||||
}
|
||||
@ -166,6 +168,17 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
||||
return newPacketConn(pc, t), err
|
||||
}
|
||||
|
||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
pc := t.instance.PacketConn(c)
|
||||
return newPacketConn(pc, t), err
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
func (t *Trojan) SupportUOT() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
|
||||
|
@ -2,13 +2,22 @@ package outbound
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
xtls "github.com/xtls/go"
|
||||
)
|
||||
|
||||
var (
|
||||
globalClientSessionCache tls.ClientSessionCache
|
||||
globalClientXSessionCache xtls.ClientSessionCache
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func tcpKeepAlive(c net.Conn) {
|
||||
@ -18,6 +27,20 @@ func tcpKeepAlive(c net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
func getClientSessionCache() tls.ClientSessionCache {
|
||||
once.Do(func() {
|
||||
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||
})
|
||||
return globalClientSessionCache
|
||||
}
|
||||
|
||||
func getClientXSessionCache() xtls.ClientSessionCache {
|
||||
once.Do(func() {
|
||||
globalClientXSessionCache = xtls.NewLRUClientSessionCache(128)
|
||||
})
|
||||
return globalClientXSessionCache
|
||||
}
|
||||
|
||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||
var buf [][]byte
|
||||
aType := uint8(metadata.AddrType)
|
||||
|
@ -12,14 +12,13 @@ import (
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/Dreamacro/clash/common/convert"
|
||||
"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 (
|
||||
@ -35,7 +34,7 @@ type Vless struct {
|
||||
// for gun mux
|
||||
gunTLSConfig *tls.Config
|
||||
gunConfig *gun.Config
|
||||
transport *http2.Transport
|
||||
transport *gun.TransportWrap
|
||||
}
|
||||
|
||||
type VlessOption struct {
|
||||
@ -46,6 +45,7 @@ type VlessOption struct {
|
||||
UUID string `proxy:"uuid"`
|
||||
Flow string `proxy:"flow,omitempty"`
|
||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||
@ -62,12 +62,6 @@ 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{
|
||||
@ -97,8 +91,10 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||
wsOpts.TLSConfig.ServerName = host
|
||||
} else {
|
||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||
convert.SetUserAgent(wsOpts.Headers)
|
||||
}
|
||||
|
||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||
case "http":
|
||||
// readability first, so just copy default TLS logic
|
||||
@ -166,7 +162,7 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
||||
|
||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||
|
||||
} else {
|
||||
} else if v.option.TLS {
|
||||
tlsOpts := vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
@ -182,6 +178,8 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
||||
|
||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (v *Vless) isXTLSEnabled() bool {
|
||||
@ -253,26 +251,36 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||
}
|
||||
|
||||
return v.ListenPacketOnStreamConn(c, metadata)
|
||||
}
|
||||
|
||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
func (v *Vless) SupportUOT() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||
var addrType byte
|
||||
var addr []byte
|
||||
switch metadata.AddrType {
|
||||
case C.AtypIPv4:
|
||||
addrType = byte(vless.AtypIPv4)
|
||||
addrType = vless.AtypIPv4
|
||||
addr = make([]byte, net.IPv4len)
|
||||
copy(addr[:], metadata.DstIP.AsSlice())
|
||||
case C.AtypIPv6:
|
||||
addrType = byte(vless.AtypIPv6)
|
||||
addrType = vless.AtypIPv6
|
||||
addr = make([]byte, net.IPv6len)
|
||||
copy(addr[:], metadata.DstIP.AsSlice())
|
||||
case C.AtypDomainName:
|
||||
addrType = byte(vless.AtypDomainName)
|
||||
addrType = vless.AtypDomainName
|
||||
addr = make([]byte, len(metadata.Host)+1)
|
||||
addr[0] = byte(len(metadata.Host))
|
||||
copy(addr[1:], []byte(metadata.Host))
|
||||
copy(addr[1:], metadata.Host)
|
||||
}
|
||||
|
||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||
@ -287,29 +295,40 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||
type vlessPacketConn struct {
|
||||
net.Conn
|
||||
rAddr net.Addr
|
||||
cache [2]byte
|
||||
remain int
|
||||
mux sync.Mutex
|
||||
cache [2]byte
|
||||
}
|
||||
|
||||
func (vc *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
func (c *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
||||
binary.BigEndian.PutUint16(c.cache[:], uint16(len(payload)))
|
||||
|
||||
if _, err := c.Conn.Write(c.cache[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return c.Conn.Write(payload)
|
||||
}
|
||||
|
||||
func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
total := len(b)
|
||||
if total == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if total < maxLength {
|
||||
return vc.writePacket(b)
|
||||
if total <= maxLength {
|
||||
return c.writePacket(b)
|
||||
}
|
||||
|
||||
offset := 0
|
||||
for {
|
||||
|
||||
for offset < total {
|
||||
cursor := offset + maxLength
|
||||
if cursor > total {
|
||||
cursor = total
|
||||
}
|
||||
|
||||
n, err := vc.writePacket(b[offset:cursor])
|
||||
n, err := c.writePacket(b[offset:cursor])
|
||||
if err != nil {
|
||||
return offset + n, err
|
||||
}
|
||||
@ -323,33 +342,32 @@ func (vc *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
vc.mux.Lock()
|
||||
defer vc.mux.Unlock()
|
||||
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
c.mux.Lock()
|
||||
defer c.mux.Unlock()
|
||||
|
||||
if vc.remain != 0 {
|
||||
if c.remain > 0 {
|
||||
length := len(b)
|
||||
if length > vc.remain {
|
||||
length = vc.remain
|
||||
if c.remain < length {
|
||||
length = c.remain
|
||||
}
|
||||
|
||||
n, err := vc.Conn.Read(b[:length])
|
||||
n, err := c.Conn.Read(b[:length])
|
||||
if err != nil {
|
||||
return 0, vc.rAddr, err
|
||||
return 0, c.rAddr, err
|
||||
}
|
||||
|
||||
vc.remain -= n
|
||||
|
||||
return n, vc.rAddr, nil
|
||||
c.remain -= n
|
||||
return n, c.rAddr, nil
|
||||
}
|
||||
|
||||
if _, err := vc.Conn.Read(b[:2]); err != nil {
|
||||
return 0, vc.rAddr, err
|
||||
if _, err := c.Conn.Read(b[:2]); err != nil {
|
||||
return 0, c.rAddr, err
|
||||
}
|
||||
|
||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
||||
if total == 0 {
|
||||
return 0, vc.rAddr, nil
|
||||
return 0, c.rAddr, nil
|
||||
}
|
||||
|
||||
length := len(b)
|
||||
@ -357,23 +375,13 @@ func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
length = total
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(vc.Conn, b[:length]); err != nil {
|
||||
return 0, vc.rAddr, errors.New("read packet error")
|
||||
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
||||
return 0, c.rAddr, errors.New("read packet error")
|
||||
}
|
||||
|
||||
vc.remain = total - length
|
||||
c.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)
|
||||
return length, c.rAddr, nil
|
||||
}
|
||||
|
||||
func NewVless(option VlessOption) (*Vless, error) {
|
||||
|
@ -10,13 +10,12 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/common/convert"
|
||||
"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 {
|
||||
@ -27,7 +26,7 @@ type Vmess struct {
|
||||
// for gun mux
|
||||
gunTLSConfig *tls.Config
|
||||
gunConfig *gun.Config
|
||||
transport *http2.Transport
|
||||
transport *gun.TransportWrap
|
||||
}
|
||||
|
||||
type VmessOption struct {
|
||||
@ -80,12 +79,6 @@ 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{
|
||||
@ -94,14 +87,13 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
Path: v.option.WSOpts.Path,
|
||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||
Headers: make(http.Header),
|
||||
}
|
||||
|
||||
if len(v.option.WSOpts.Headers) != 0 {
|
||||
header := http.Header{}
|
||||
for key, value := range v.option.WSOpts.Headers {
|
||||
header.Add(key, value)
|
||||
wsOpts.Headers.Add(key, value)
|
||||
}
|
||||
wsOpts.Headers = header
|
||||
}
|
||||
|
||||
if v.option.TLS {
|
||||
@ -116,6 +108,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||
wsOpts.TLSConfig.ServerName = host
|
||||
}
|
||||
} else {
|
||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||
convert.SetUserAgent(wsOpts.Headers)
|
||||
}
|
||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||
case "http":
|
||||
@ -135,6 +130,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
http.Header(v.option.HTTPOpts.Headers).Set("Host", convert.RandHost())
|
||||
convert.SetUserAgent(v.option.HTTPOpts.Headers)
|
||||
}
|
||||
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
@ -260,9 +258,19 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||
}
|
||||
|
||||
return v.ListenPacketOnStreamConn(c, metadata)
|
||||
}
|
||||
|
||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||
}
|
||||
|
||||
// SupportUOT implements C.ProxyAdapter
|
||||
func (v *Vmess) SupportUOT() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
security := strings.ToLower(option.Cipher)
|
||||
client, err := vmess.NewClient(vmess.Config{
|
||||
|
@ -1,24 +0,0 @@
|
||||
package outboundgroup
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/provider"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultGetProxiesDuration = time.Second * 5
|
||||
)
|
||||
|
||||
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
||||
proxies := []C.Proxy{}
|
||||
for _, provider := range providers {
|
||||
if touch {
|
||||
proxies = append(proxies, provider.ProxiesWithTouch()...)
|
||||
} else {
|
||||
proxies = append(proxies, provider.Proxies()...)
|
||||
}
|
||||
}
|
||||
return proxies
|
||||
}
|
@ -3,19 +3,20 @@ package outboundgroup
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"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 Fallback struct {
|
||||
*outbound.Base
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
single *singledo.Single[[]C.Proxy]
|
||||
providers []provider.ProxyProvider
|
||||
testUrl string
|
||||
selected string
|
||||
}
|
||||
|
||||
func (f *Fallback) Now() string {
|
||||
@ -29,7 +30,11 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||
if err == nil {
|
||||
c.AppendToChains(f)
|
||||
f.onDialSuccess()
|
||||
} else {
|
||||
f.onDialFailed()
|
||||
}
|
||||
|
||||
return c, err
|
||||
}
|
||||
|
||||
@ -40,6 +45,7 @@ func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
||||
if err == nil {
|
||||
pc.AppendToChains(f)
|
||||
}
|
||||
|
||||
return pc, err
|
||||
}
|
||||
|
||||
@ -55,8 +61,8 @@ func (f *Fallback) SupportUDP() bool {
|
||||
|
||||
// MarshalJSON implements C.ProxyAdapter
|
||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range f.proxies(false) {
|
||||
all := []string{}
|
||||
for _, proxy := range f.GetProxies(false) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
@ -72,35 +78,57 @@ func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||
return proxy
|
||||
}
|
||||
|
||||
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
||||
elm, _, _ := f.single.Do(func() ([]C.Proxy, error) {
|
||||
return getProvidersProxies(f.providers, touch), nil
|
||||
})
|
||||
|
||||
return elm
|
||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||
proxies := f.GetProxies(touch)
|
||||
al := proxies[0]
|
||||
for i := len(proxies) - 1; i > -1; i-- {
|
||||
proxy := proxies[i]
|
||||
if proxy.Name() == f.selected && proxy.Alive() {
|
||||
return proxy
|
||||
}
|
||||
if proxy.Alive() {
|
||||
al = proxy
|
||||
}
|
||||
}
|
||||
return al
|
||||
}
|
||||
|
||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||
proxies := f.proxies(touch)
|
||||
for _, proxy := range proxies {
|
||||
if proxy.Alive() {
|
||||
return proxy
|
||||
func (f *Fallback) Set(name string) error {
|
||||
var p C.Proxy
|
||||
for _, proxy := range f.GetProxies(false) {
|
||||
if proxy.Name() == name {
|
||||
p = proxy
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return proxies[0]
|
||||
if p == nil {
|
||||
return errors.New("proxy not exist")
|
||||
}
|
||||
|
||||
f.selected = name
|
||||
if !p.Alive() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||
defer cancel()
|
||||
_, _ = p.URLTest(ctx, f.testUrl)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||
return &Fallback{
|
||||
Base: outbound.NewBase(outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Fallback,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Fallback,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
},
|
||||
option.Filter,
|
||||
providers,
|
||||
}),
|
||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||
providers: providers,
|
||||
disableUDP: option.DisableUDP,
|
||||
testUrl: option.URL,
|
||||
}
|
||||
}
|
||||
|
189
adapter/outboundgroup/groupbase.go
Normal file
189
adapter/outboundgroup/groupbase.go
Normal file
@ -0,0 +1,189 @@
|
||||
package outboundgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
"github.com/Dreamacro/clash/constant/provider"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
"github.com/dlclark/regexp2"
|
||||
"go.uber.org/atomic"
|
||||
)
|
||||
|
||||
type GroupBase struct {
|
||||
*outbound.Base
|
||||
filter *regexp2.Regexp
|
||||
providers []provider.ProxyProvider
|
||||
versions sync.Map // map[string]uint
|
||||
proxies sync.Map // map[string][]C.Proxy
|
||||
failedTestMux sync.Mutex
|
||||
failedTimes int
|
||||
failedTime time.Time
|
||||
failedTesting *atomic.Bool
|
||||
}
|
||||
|
||||
type GroupBaseOption struct {
|
||||
outbound.BaseOption
|
||||
filter string
|
||||
providers []provider.ProxyProvider
|
||||
}
|
||||
|
||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||
var filter *regexp2.Regexp = nil
|
||||
if opt.filter != "" {
|
||||
filter = regexp2.MustCompile(opt.filter, 0)
|
||||
}
|
||||
return &GroupBase{
|
||||
Base: outbound.NewBase(opt.BaseOption),
|
||||
filter: filter,
|
||||
providers: opt.providers,
|
||||
failedTesting: atomic.NewBool(false),
|
||||
}
|
||||
}
|
||||
|
||||
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||
if gb.filter == nil {
|
||||
var proxies []C.Proxy
|
||||
for _, pd := range gb.providers {
|
||||
if touch {
|
||||
pd.Touch()
|
||||
}
|
||||
proxies = append(proxies, pd.Proxies()...)
|
||||
}
|
||||
if len(proxies) == 0 {
|
||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||
}
|
||||
return proxies
|
||||
}
|
||||
|
||||
for _, pd := range gb.providers {
|
||||
if touch {
|
||||
pd.Touch()
|
||||
}
|
||||
|
||||
if pd.VehicleType() == types.Compatible {
|
||||
gb.proxies.Store(pd.Name(), pd.Proxies())
|
||||
gb.versions.Store(pd.Name(), pd.Version())
|
||||
continue
|
||||
}
|
||||
|
||||
if version, ok := gb.versions.Load(pd.Name()); !ok || version != pd.Version() {
|
||||
var (
|
||||
proxies []C.Proxy
|
||||
newProxies []C.Proxy
|
||||
)
|
||||
|
||||
proxies = pd.Proxies()
|
||||
|
||||
for _, p := range proxies {
|
||||
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
||||
newProxies = append(newProxies, p)
|
||||
}
|
||||
}
|
||||
|
||||
gb.proxies.Store(pd.Name(), newProxies)
|
||||
gb.versions.Store(pd.Name(), pd.Version())
|
||||
}
|
||||
}
|
||||
var proxies []C.Proxy
|
||||
gb.proxies.Range(func(key, value any) bool {
|
||||
proxies = append(proxies, value.([]C.Proxy)...)
|
||||
return true
|
||||
})
|
||||
if len(proxies) == 0 {
|
||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||
}
|
||||
return proxies
|
||||
}
|
||||
|
||||
func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16, error) {
|
||||
var wg sync.WaitGroup
|
||||
var lock sync.Mutex
|
||||
mp := map[string]uint16{}
|
||||
proxies := gb.GetProxies(false)
|
||||
for _, proxy := range proxies {
|
||||
proxy := proxy
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
delay, err := proxy.URLTest(ctx, url)
|
||||
lock.Lock()
|
||||
if err == nil {
|
||||
mp[proxy.Name()] = delay
|
||||
}
|
||||
lock.Unlock()
|
||||
|
||||
wg.Done()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if len(mp) == 0 {
|
||||
return mp, fmt.Errorf("get delay: all proxies timeout")
|
||||
} else {
|
||||
return mp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (gb *GroupBase) onDialFailed() {
|
||||
if gb.failedTesting.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
gb.failedTestMux.Lock()
|
||||
defer gb.failedTestMux.Unlock()
|
||||
|
||||
gb.failedTimes++
|
||||
if gb.failedTimes == 1 {
|
||||
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
||||
gb.failedTime = time.Now()
|
||||
} else {
|
||||
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
||||
return
|
||||
}
|
||||
|
||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||
gb.failedTesting.Store(true)
|
||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||
wg := sync.WaitGroup{}
|
||||
for _, proxyProvider := range gb.providers {
|
||||
wg.Add(1)
|
||||
proxyProvider := proxyProvider
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
proxyProvider.HealthCheck()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
gb.failedTesting.Store(false)
|
||||
gb.failedTimes = 0
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
||||
return 5 * time.Second.Milliseconds()
|
||||
}
|
||||
|
||||
func (gb *GroupBase) onDialSuccess() {
|
||||
if !gb.failedTesting.Load() {
|
||||
gb.failedTimes = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (gb *GroupBase) maxFailedTimes() int {
|
||||
return 5
|
||||
}
|
||||
|
||||
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
||||
return 5 * time.Second
|
||||
}
|
@ -6,24 +6,22 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"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
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
single *singledo.Single[[]C.Proxy]
|
||||
providers []provider.ProxyProvider
|
||||
strategyFn strategyFn
|
||||
}
|
||||
|
||||
@ -39,6 +37,10 @@ func parseStrategy(config map[string]any) string {
|
||||
}
|
||||
|
||||
func getKey(metadata *C.Metadata) string {
|
||||
if metadata == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if metadata.Host != "" {
|
||||
// ip host
|
||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||
@ -57,6 +59,16 @@ func getKey(metadata *C.Metadata) string {
|
||||
return metadata.DstIP.String()
|
||||
}
|
||||
|
||||
func getKeyWithSrcAndDst(metadata *C.Metadata) string {
|
||||
dst := getKey(metadata)
|
||||
src := ""
|
||||
if metadata != nil {
|
||||
src = metadata.SrcIP.String()
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s%s", src, dst)
|
||||
}
|
||||
|
||||
func jumpHash(key uint64, buckets int32) int32 {
|
||||
var b, j int64
|
||||
|
||||
@ -74,6 +86,9 @@ func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, op
|
||||
defer func() {
|
||||
if err == nil {
|
||||
c.AppendToChains(lb)
|
||||
lb.onDialSuccess()
|
||||
} else {
|
||||
lb.onDialFailed()
|
||||
}
|
||||
}()
|
||||
|
||||
@ -133,24 +148,51 @@ func strategyConsistentHashing() strategyFn {
|
||||
}
|
||||
}
|
||||
|
||||
// Unwrap implements C.ProxyAdapter
|
||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||
proxies := lb.proxies(true)
|
||||
return lb.strategyFn(proxies, metadata)
|
||||
func strategyStickySessions() strategyFn {
|
||||
ttl := time.Minute * 10
|
||||
maxRetry := 5
|
||||
lruCache := cache.NewLRUCache[uint64, int](
|
||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||
cache.WithSize[uint64, int](1000))
|
||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||
length := len(proxies)
|
||||
idx, has := lruCache.Get(key)
|
||||
if !has {
|
||||
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||
}
|
||||
|
||||
nowIdx := idx
|
||||
for i := 1; i < maxRetry; i++ {
|
||||
proxy := proxies[nowIdx]
|
||||
if proxy.Alive() {
|
||||
if nowIdx != idx {
|
||||
lruCache.Delete(key)
|
||||
lruCache.Set(key, nowIdx)
|
||||
}
|
||||
|
||||
return proxy
|
||||
} else {
|
||||
nowIdx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||
}
|
||||
}
|
||||
|
||||
lruCache.Delete(key)
|
||||
lruCache.Set(key, 0)
|
||||
return proxies[0]
|
||||
}
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
||||
elm, _, _ := lb.single.Do(func() ([]C.Proxy, error) {
|
||||
return getProvidersProxies(lb.providers, touch), nil
|
||||
})
|
||||
|
||||
return elm
|
||||
// Unwrap implements C.ProxyAdapter
|
||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||
proxies := lb.GetProxies(true)
|
||||
return lb.strategyFn(proxies, metadata)
|
||||
}
|
||||
|
||||
// MarshalJSON implements C.ProxyAdapter
|
||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range lb.proxies(false) {
|
||||
for _, proxy := range lb.GetProxies(false) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
@ -166,18 +208,22 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
||||
strategyFn = strategyConsistentHashing()
|
||||
case "round-robin":
|
||||
strategyFn = strategyRoundRobin()
|
||||
case "sticky-sessions":
|
||||
strategyFn = strategyStickySessions()
|
||||
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,
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.LoadBalance,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
},
|
||||
option.Filter,
|
||||
providers,
|
||||
}),
|
||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||
providers: providers,
|
||||
strategyFn: strategyFn,
|
||||
disableUDP: option.DisableUDP,
|
||||
}, nil
|
||||
|
@ -29,6 +29,7 @@ type GroupCommonOption struct {
|
||||
Interval int `group:"interval,omitempty"`
|
||||
Lazy bool `group:"lazy,omitempty"`
|
||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||
Filter string `group:"filter,omitempty"`
|
||||
}
|
||||
|
||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||
@ -74,8 +75,12 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
providers = append(providers, pd)
|
||||
providersMap[groupName] = pd
|
||||
} else {
|
||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||
return nil, errMissHealthCheck
|
||||
if groupOption.URL == "" {
|
||||
groupOption.URL = "http://www.gstatic.com/generate_204"
|
||||
}
|
||||
|
||||
if groupOption.Interval == 0 {
|
||||
groupOption.Interval = 300
|
||||
}
|
||||
|
||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||
@ -95,6 +100,8 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
return nil, err
|
||||
}
|
||||
providers = append(providers, list...)
|
||||
} else {
|
||||
groupOption.Filter = ""
|
||||
}
|
||||
|
||||
var group C.ProxyAdapter
|
||||
|
@ -6,26 +6,18 @@ import (
|
||||
"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
|
||||
*GroupBase
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
proxies, chainProxies := r.proxies(metadata, true)
|
||||
|
||||
switch len(proxies) {
|
||||
case 0:
|
||||
@ -63,13 +55,86 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||
}
|
||||
|
||||
return outbound.NewConn(c, r), nil
|
||||
conn := outbound.NewConn(c, last)
|
||||
|
||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||
conn.AppendToChains(chainProxies[i])
|
||||
}
|
||||
|
||||
conn.AppendToChains(r)
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// ListenPacketContext implements C.ProxyAdapter
|
||||
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||
proxies, chainProxies := r.proxies(metadata, true)
|
||||
|
||||
switch len(proxies) {
|
||||
case 0:
|
||||
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||
case 1:
|
||||
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||
}
|
||||
|
||||
first := proxies[0]
|
||||
last := proxies[len(proxies)-1]
|
||||
|
||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||
}
|
||||
tcpKeepAlive(c)
|
||||
|
||||
var currentMeta *C.Metadata
|
||||
for _, proxy := range proxies[1:] {
|
||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c, err = first.StreamConn(c, currentMeta)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||
}
|
||||
|
||||
first = proxy
|
||||
}
|
||||
|
||||
c, err = last.StreamConn(c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||
}
|
||||
|
||||
var pc C.PacketConn
|
||||
pc, err = last.ListenPacketOnStreamConn(c, metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||
}
|
||||
|
||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||
pc.AppendToChains(chainProxies[i])
|
||||
}
|
||||
|
||||
pc.AppendToChains(r)
|
||||
|
||||
return pc, nil
|
||||
}
|
||||
|
||||
// SupportUDP implements C.ProxyAdapter
|
||||
func (r *Relay) SupportUDP() bool {
|
||||
proxies, _ := r.proxies(nil, false)
|
||||
if len(proxies) == 0 { // C.Direct
|
||||
return true
|
||||
}
|
||||
last := proxies[len(proxies)-1]
|
||||
return last.SupportUDP() && last.SupportUOT()
|
||||
}
|
||||
|
||||
// MarshalJSON implements C.ProxyAdapter
|
||||
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range r.rawProxies(false) {
|
||||
all := []string{}
|
||||
for _, proxy := range r.GetProxies(false) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
@ -78,37 +143,49 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||
elm, _, _ := r.single.Do(func() ([]C.Proxy, error) {
|
||||
return getProvidersProxies(r.providers, touch), nil
|
||||
})
|
||||
func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy) {
|
||||
rawProxies := r.GetProxies(touch)
|
||||
|
||||
return elm
|
||||
}
|
||||
var proxies []C.Proxy
|
||||
var chainProxies []C.Proxy
|
||||
var targetProxies []C.Proxy
|
||||
|
||||
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
|
||||
proxies := r.rawProxies(touch)
|
||||
|
||||
for n, proxy := range proxies {
|
||||
for n, proxy := range rawProxies {
|
||||
proxies = append(proxies, proxy)
|
||||
chainProxies = append(chainProxies, proxy)
|
||||
subproxy := proxy.Unwrap(metadata)
|
||||
for subproxy != nil {
|
||||
chainProxies = append(chainProxies, subproxy)
|
||||
proxies[n] = subproxy
|
||||
subproxy = subproxy.Unwrap(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
return proxies
|
||||
for _, proxy := range proxies {
|
||||
if proxy.Type() != C.Direct && proxy.Type() != C.Compatible {
|
||||
targetProxies = append(targetProxies, proxy)
|
||||
}
|
||||
}
|
||||
|
||||
return targetProxies, chainProxies
|
||||
}
|
||||
|
||||
func (r *Relay) Addr() string {
|
||||
proxies, _ := r.proxies(nil, true)
|
||||
return proxies[len(proxies)-1].Addr()
|
||||
}
|
||||
|
||||
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,
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Relay,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
},
|
||||
"",
|
||||
providers,
|
||||
}),
|
||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||
providers: providers,
|
||||
}
|
||||
}
|
||||
|
@ -6,18 +6,15 @@ import (
|
||||
"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
|
||||
*GroupBase
|
||||
disableUDP bool
|
||||
single *singledo.Single[C.Proxy]
|
||||
selected string
|
||||
providers []provider.ProxyProvider
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@ -49,8 +46,8 @@ func (s *Selector) SupportUDP() bool {
|
||||
|
||||
// MarshalJSON implements C.ProxyAdapter
|
||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||
all := []string{}
|
||||
for _, proxy := range s.GetProxies(false) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
|
||||
@ -66,10 +63,9 @@ func (s *Selector) Now() string {
|
||||
}
|
||||
|
||||
func (s *Selector) Set(name string) error {
|
||||
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||
for _, proxy := range s.GetProxies(false) {
|
||||
if proxy.Name() == name {
|
||||
s.selected = name
|
||||
s.single.Reset()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@ -78,37 +74,34 @@ func (s *Selector) Set(name string) error {
|
||||
}
|
||||
|
||||
// Unwrap implements C.ProxyAdapter
|
||||
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
||||
return s.selectedProxy(true)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
proxies := s.GetProxies(touch)
|
||||
for _, proxy := range proxies {
|
||||
if proxy.Name() == s.selected {
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
|
||||
return proxies[0], nil
|
||||
})
|
||||
|
||||
return elm
|
||||
return proxies[0]
|
||||
}
|
||||
|
||||
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,
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.Selector,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
},
|
||||
option.Filter,
|
||||
providers,
|
||||
}),
|
||||
single: singledo.NewSingle[C.Proxy](defaultGetProxiesDuration),
|
||||
providers: providers,
|
||||
selected: selected,
|
||||
selected: "COMPATIBLE",
|
||||
disableUDP: option.DisableUDP,
|
||||
}
|
||||
}
|
||||
|
@ -21,13 +21,11 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
||||
}
|
||||
|
||||
type URLTest struct {
|
||||
*outbound.Base
|
||||
*GroupBase
|
||||
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 {
|
||||
@ -39,6 +37,9 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||
if err == nil {
|
||||
c.AppendToChains(u)
|
||||
u.onDialSuccess()
|
||||
} else {
|
||||
u.onDialFailed()
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
@ -49,25 +50,18 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
||||
if err == nil {
|
||||
pc.AppendToChains(u)
|
||||
}
|
||||
|
||||
return pc, err
|
||||
}
|
||||
|
||||
// Unwrap implements C.ProxyAdapter
|
||||
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
||||
return u.fast(true)
|
||||
}
|
||||
|
||||
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)
|
||||
proxies := u.GetProxies(touch)
|
||||
fast := proxies[0]
|
||||
min := fast.LastDelay()
|
||||
fastNotExist := true
|
||||
@ -110,8 +104,8 @@ func (u *URLTest) SupportUDP() bool {
|
||||
|
||||
// MarshalJSON implements C.ProxyAdapter
|
||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range u.proxies(false) {
|
||||
all := []string{}
|
||||
for _, proxy := range u.GetProxies(false) {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
@ -136,15 +130,18 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||
|
||||
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||
urlTest := &URLTest{
|
||||
Base: outbound.NewBase(outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.URLTest,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
GroupBase: NewGroupBase(GroupBaseOption{
|
||||
outbound.BaseOption{
|
||||
Name: option.Name,
|
||||
Type: C.URLTest,
|
||||
Interface: option.Interface,
|
||||
RoutingMark: option.RoutingMark,
|
||||
},
|
||||
|
||||
option.Filter,
|
||||
providers,
|
||||
}),
|
||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||
providers: providers,
|
||||
disableUDP: option.DisableUDP,
|
||||
}
|
||||
|
||||
|
@ -24,6 +24,7 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
||||
DstIP: netip.Addr{},
|
||||
DstPort: port,
|
||||
}
|
||||
err = nil
|
||||
return
|
||||
} else if ip.Is4() {
|
||||
addr = &C.Metadata{
|
||||
@ -50,3 +51,7 @@ func tcpKeepAlive(c net.Conn) {
|
||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
type SelectAble interface {
|
||||
Set(string) error
|
||||
}
|
||||
|
@ -81,6 +81,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||
break
|
||||
}
|
||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||
case "hysteria":
|
||||
hyOption := &outbound.HysteriaOption{}
|
||||
err = decoder.Decode(mapping, hyOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy, err = outbound.NewHysteria(*hyOption)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||
}
|
||||
|
@ -16,61 +16,69 @@ var (
|
||||
dirMode os.FileMode = 0o755
|
||||
)
|
||||
|
||||
type parser = func([]byte) (any, error)
|
||||
type parser[V any] func([]byte) (V, error)
|
||||
|
||||
type fetcher struct {
|
||||
type fetcher[V any] struct {
|
||||
name string
|
||||
vehicle types.Vehicle
|
||||
updatedAt *time.Time
|
||||
ticker *time.Ticker
|
||||
done chan struct{}
|
||||
hash [16]byte
|
||||
parser parser
|
||||
onUpdate func(any)
|
||||
parser parser[V]
|
||||
interval time.Duration
|
||||
onUpdate func(V)
|
||||
}
|
||||
|
||||
func (f *fetcher) Name() string {
|
||||
func (f *fetcher[V]) Name() string {
|
||||
return f.name
|
||||
}
|
||||
|
||||
func (f *fetcher) VehicleType() types.VehicleType {
|
||||
func (f *fetcher[V]) VehicleType() types.VehicleType {
|
||||
return f.vehicle.Type()
|
||||
}
|
||||
|
||||
func (f *fetcher) Initial() (any, error) {
|
||||
func (f *fetcher[V]) Initial() (V, 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
|
||||
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
||||
defer func() {
|
||||
log.Infoln("[Provider] %s's proxies not updated for a long time, force refresh", f.Name())
|
||||
go f.Update()
|
||||
}()
|
||||
}
|
||||
} else {
|
||||
buf, err = f.vehicle.Read()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return getZero[V](), err
|
||||
}
|
||||
|
||||
proxies, err := f.parser(buf)
|
||||
if err != nil {
|
||||
if !isLocal {
|
||||
return nil, err
|
||||
return getZero[V](), err
|
||||
}
|
||||
|
||||
// parse local file error, fallback to remote
|
||||
buf, err = f.vehicle.Read()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return getZero[V](), err
|
||||
}
|
||||
|
||||
proxies, err = f.parser(buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return getZero[V](), err
|
||||
}
|
||||
|
||||
isLocal = false
|
||||
@ -78,7 +86,7 @@ func (f *fetcher) Initial() (any, error) {
|
||||
|
||||
if f.vehicle.Type() != types.File && !isLocal {
|
||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||
return nil, err
|
||||
return getZero[V](), err
|
||||
}
|
||||
}
|
||||
|
||||
@ -92,10 +100,10 @@ func (f *fetcher) Initial() (any, error) {
|
||||
return proxies, nil
|
||||
}
|
||||
|
||||
func (f *fetcher) Update() (any, bool, error) {
|
||||
func (f *fetcher[V]) Update() (V, bool, error) {
|
||||
buf, err := f.vehicle.Read()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return getZero[V](), false, err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
@ -103,17 +111,17 @@ func (f *fetcher) Update() (any, bool, error) {
|
||||
if bytes.Equal(f.hash[:], hash[:]) {
|
||||
f.updatedAt = &now
|
||||
os.Chtimes(f.vehicle.Path(), now, now)
|
||||
return nil, true, nil
|
||||
return getZero[V](), true, nil
|
||||
}
|
||||
|
||||
proxies, err := f.parser(buf)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return getZero[V](), false, err
|
||||
}
|
||||
|
||||
if f.vehicle.Type() != types.File {
|
||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||
return nil, false, err
|
||||
return getZero[V](), false, err
|
||||
}
|
||||
}
|
||||
|
||||
@ -123,14 +131,14 @@ func (f *fetcher) Update() (any, bool, error) {
|
||||
return proxies, false, nil
|
||||
}
|
||||
|
||||
func (f *fetcher) Destroy() error {
|
||||
func (f *fetcher[V]) Destroy() error {
|
||||
if f.ticker != nil {
|
||||
f.done <- struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fetcher) pullLoop() {
|
||||
func (f *fetcher[V]) pullLoop() {
|
||||
for {
|
||||
select {
|
||||
case <-f.ticker.C:
|
||||
@ -168,13 +176,13 @@ func safeWrite(path string, buf []byte) error {
|
||||
return os.WriteFile(path, buf, fileMode)
|
||||
}
|
||||
|
||||
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
|
||||
func newFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser parser[V], onUpdate func(V)) *fetcher[V] {
|
||||
var ticker *time.Ticker
|
||||
if interval != 0 {
|
||||
ticker = time.NewTicker(interval)
|
||||
}
|
||||
|
||||
return &fetcher{
|
||||
return &fetcher[V]{
|
||||
name: name,
|
||||
ticker: ticker,
|
||||
vehicle: vehicle,
|
||||
@ -183,3 +191,8 @@ func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, pars
|
||||
onUpdate: onUpdate,
|
||||
}
|
||||
}
|
||||
|
||||
func getZero[V any]() V {
|
||||
var result V
|
||||
return result
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/common/batch"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
)
|
||||
|
||||
@ -32,9 +31,7 @@ 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()
|
||||
time.Sleep(30 * time.Second)
|
||||
hc.check()
|
||||
}()
|
||||
|
||||
|
@ -4,15 +4,16 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"math"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter"
|
||||
"github.com/Dreamacro/clash/common/convert"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
"github.com/dlclark/regexp2"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -23,15 +24,16 @@ type ProxySchema struct {
|
||||
Proxies []map[string]any `yaml:"proxies"`
|
||||
}
|
||||
|
||||
// for auto gc
|
||||
// ProxySetProvider for auto gc
|
||||
type ProxySetProvider struct {
|
||||
*proxySetProvider
|
||||
}
|
||||
|
||||
type proxySetProvider struct {
|
||||
*fetcher
|
||||
*fetcher[[]C.Proxy]
|
||||
proxies []C.Proxy
|
||||
healthCheck *HealthCheck
|
||||
version uint
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||
@ -44,6 +46,10 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) Version() uint {
|
||||
return pp.version
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) Name() string {
|
||||
return pp.name
|
||||
}
|
||||
@ -65,7 +71,6 @@ func (pp *proxySetProvider) Initial() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pp.onUpdate(elm)
|
||||
return nil
|
||||
}
|
||||
@ -78,26 +83,25 @@ func (pp *proxySetProvider) Proxies() []C.Proxy {
|
||||
return pp.proxies
|
||||
}
|
||||
|
||||
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
||||
func (pp *proxySetProvider) Touch() {
|
||||
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()
|
||||
defer func() { go pp.healthCheck.check() }()
|
||||
}
|
||||
}
|
||||
|
||||
func stopProxyProvider(pd *ProxySetProvider) {
|
||||
pd.healthCheck.close()
|
||||
pd.fetcher.Destroy()
|
||||
_ = pd.fetcher.Destroy()
|
||||
}
|
||||
|
||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||
filterReg, err := regexp.Compile(filter)
|
||||
filterReg, err := regexp2.Compile(filter, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||
}
|
||||
@ -111,45 +115,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
||||
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)
|
||||
fetcher := newFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg), proxiesOnUpdate(pd))
|
||||
pd.fetcher = fetcher
|
||||
|
||||
wrapper := &ProxySetProvider{pd}
|
||||
@ -157,7 +123,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
||||
return wrapper, nil
|
||||
}
|
||||
|
||||
// for auto gc
|
||||
// CompatibleProvider for auto gc
|
||||
type CompatibleProvider struct {
|
||||
*compatibleProvider
|
||||
}
|
||||
@ -166,6 +132,7 @@ type compatibleProvider struct {
|
||||
name string
|
||||
healthCheck *HealthCheck
|
||||
proxies []C.Proxy
|
||||
version uint
|
||||
}
|
||||
|
||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||
@ -177,6 +144,10 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (cp *compatibleProvider) Version() uint {
|
||||
return cp.version
|
||||
}
|
||||
|
||||
func (cp *compatibleProvider) Name() string {
|
||||
return cp.name
|
||||
}
|
||||
@ -205,9 +176,8 @@ func (cp *compatibleProvider) Proxies() []C.Proxy {
|
||||
return cp.proxies
|
||||
}
|
||||
|
||||
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
||||
func (cp *compatibleProvider) Touch() {
|
||||
cp.healthCheck.touch()
|
||||
return cp.Proxies()
|
||||
}
|
||||
|
||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||
@ -233,3 +203,55 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
||||
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||
return wrapper, nil
|
||||
}
|
||||
|
||||
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
||||
return func(elm []C.Proxy) {
|
||||
pd.setProxies(elm)
|
||||
if pd.version == math.MaxUint {
|
||||
pd.version = 0
|
||||
} else {
|
||||
pd.version++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) parser[[]C.Proxy] {
|
||||
return func(buf []byte) ([]C.Proxy, error) {
|
||||
schema := &ProxySchema{}
|
||||
|
||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||
if err1 != nil {
|
||||
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
||||
}
|
||||
schema.Proxies = proxies
|
||||
}
|
||||
|
||||
if schema.Proxies == nil {
|
||||
return nil, errors.New("file must have a `proxies` field")
|
||||
}
|
||||
|
||||
proxies := []C.Proxy{}
|
||||
for idx, mapping := range schema.Proxies {
|
||||
name, ok := mapping["name"]
|
||||
mat, _ := filterReg.FindStringMatch(name.(string))
|
||||
if ok && len(filter) > 0 && mat == nil {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
@ -3,13 +3,11 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
netHttp "github.com/Dreamacro/clash/component/http"
|
||||
types "github.com/Dreamacro/clash/constant/provider"
|
||||
)
|
||||
|
||||
@ -49,47 +47,16 @@ func (h *HTTPVehicle) Path() string {
|
||||
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||
defer cancel()
|
||||
|
||||
uri, err := url.Parse(h.url)
|
||||
resp, err := netHttp.HttpRequest(ctx, h.url, http.MethodGet, nil, nil)
|
||||
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
|
||||
}
|
||||
|
||||
|
28
check_amd64.sh
Normal file
28
check_amd64.sh
Normal file
@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
flags=$(grep '^flags\b' </proc/cpuinfo | head -n 1)
|
||||
flags=" ${flags#*:} "
|
||||
|
||||
has_flags () {
|
||||
for flag; do
|
||||
case "$flags" in
|
||||
*" $flag "*) :;;
|
||||
*) return 1;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
determine_level () {
|
||||
level=0
|
||||
has_flags lm cmov cx8 fpu fxsr mmx syscall sse2 || return 0
|
||||
level=1
|
||||
has_flags cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 || return 0
|
||||
level=2
|
||||
has_flags avx avx2 bmi1 bmi2 f16c fma abm movbe xsave || return 0
|
||||
level=3
|
||||
has_flags avx512f avx512bw avx512cd avx512dq avx512vl || return 0
|
||||
level=4
|
||||
}
|
||||
|
||||
determine_level
|
||||
echo "Your CPU supports amd64-v$level"
|
||||
return $level
|
@ -1,303 +0,0 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var currentSerialNumber = time.Now().Unix()
|
||||
|
||||
type Config struct {
|
||||
ca *x509.Certificate
|
||||
caPrivateKey *rsa.PrivateKey
|
||||
|
||||
roots *x509.CertPool
|
||||
|
||||
privateKey *rsa.PrivateKey
|
||||
|
||||
validity time.Duration
|
||||
keyID []byte
|
||||
organization string
|
||||
|
||||
certsStorage CertsStorage
|
||||
}
|
||||
|
||||
type CertsStorage interface {
|
||||
Get(key string) (*tls.Certificate, bool)
|
||||
|
||||
Set(key string, cert *tls.Certificate)
|
||||
}
|
||||
|
||||
func NewAuthority(name, organization string, validity time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pub := privateKey.Public()
|
||||
|
||||
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
h := sha1.New()
|
||||
_, err = h.Write(pkixPub)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
keyID := h.Sum(nil)
|
||||
|
||||
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
||||
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(serial),
|
||||
Subject: pkix.Name{
|
||||
CommonName: name,
|
||||
Organization: []string{organization},
|
||||
},
|
||||
SubjectKeyId: keyID,
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
NotBefore: time.Now().Add(-validity),
|
||||
NotAfter: time.Now().Add(validity),
|
||||
DNSNames: []string{name},
|
||||
IsCA: true,
|
||||
}
|
||||
|
||||
raw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, privateKey)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
x509c, err := x509.ParseCertificate(raw)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return x509c, privateKey, nil
|
||||
}
|
||||
|
||||
func NewConfig(ca *x509.Certificate, caPrivateKey *rsa.PrivateKey) (*Config, error) {
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(ca)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub := privateKey.Public()
|
||||
|
||||
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := sha1.New()
|
||||
_, err = h.Write(pkixPub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyID := h.Sum(nil)
|
||||
|
||||
return &Config{
|
||||
ca: ca,
|
||||
caPrivateKey: caPrivateKey,
|
||||
privateKey: privateKey,
|
||||
keyID: keyID,
|
||||
validity: time.Hour,
|
||||
organization: "Clash",
|
||||
certsStorage: NewDomainTrieCertsStorage(),
|
||||
roots: roots,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Config) GetCA() *x509.Certificate {
|
||||
return c.ca
|
||||
}
|
||||
|
||||
func (c *Config) SetOrganization(organization string) {
|
||||
c.organization = organization
|
||||
}
|
||||
|
||||
func (c *Config) SetValidity(validity time.Duration) {
|
||||
c.validity = validity
|
||||
}
|
||||
|
||||
func (c *Config) NewTLSConfigForHost(hostname string) *tls.Config {
|
||||
tlsConfig := &tls.Config{
|
||||
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
host := clientHello.ServerName
|
||||
if host == "" {
|
||||
host = hostname
|
||||
}
|
||||
|
||||
return c.GetOrCreateCert(host)
|
||||
},
|
||||
NextProtos: []string{"http/1.1"},
|
||||
}
|
||||
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
|
||||
return tlsConfig
|
||||
}
|
||||
|
||||
func (c *Config) GetOrCreateCert(hostname string, ips ...net.IP) (*tls.Certificate, error) {
|
||||
var leaf *x509.Certificate
|
||||
tlsCertificate, ok := c.certsStorage.Get(hostname)
|
||||
if ok {
|
||||
leaf = tlsCertificate.Leaf
|
||||
if _, err := leaf.Verify(x509.VerifyOptions{
|
||||
DNSName: hostname,
|
||||
Roots: c.roots,
|
||||
}); err == nil {
|
||||
return tlsCertificate, nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
key = hostname
|
||||
topHost = hostname
|
||||
wildcardHost = "*." + hostname
|
||||
dnsNames []string
|
||||
)
|
||||
|
||||
if ip := net.ParseIP(hostname); ip != nil {
|
||||
ips = append(ips, ip)
|
||||
} else {
|
||||
parts := strings.Split(hostname, ".")
|
||||
l := len(parts)
|
||||
|
||||
if leaf != nil {
|
||||
dnsNames = append(dnsNames, leaf.DNSNames...)
|
||||
}
|
||||
|
||||
if l > 2 {
|
||||
topIndex := l - 2
|
||||
topHost = strings.Join(parts[topIndex:], ".")
|
||||
|
||||
for i := topIndex; i > 0; i-- {
|
||||
wildcardHost = "*." + strings.Join(parts[i:], ".")
|
||||
|
||||
if i == topIndex && (len(dnsNames) == 0 || dnsNames[0] != topHost) {
|
||||
dnsNames = append(dnsNames, topHost, wildcardHost)
|
||||
} else if !hasDnsNames(dnsNames, wildcardHost) {
|
||||
dnsNames = append(dnsNames, wildcardHost)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
dnsNames = append(dnsNames, topHost, wildcardHost)
|
||||
}
|
||||
|
||||
key = "+." + topHost
|
||||
}
|
||||
|
||||
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
||||
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(serial),
|
||||
Subject: pkix.Name{
|
||||
CommonName: topHost,
|
||||
Organization: []string{c.organization},
|
||||
},
|
||||
SubjectKeyId: c.keyID,
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
NotBefore: time.Now().Add(-c.validity),
|
||||
NotAfter: time.Now().Add(c.validity),
|
||||
DNSNames: dnsNames,
|
||||
IPAddresses: ips,
|
||||
}
|
||||
|
||||
raw, err := x509.CreateCertificate(rand.Reader, tmpl, c.ca, c.privateKey.Public(), c.caPrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
x509c, err := x509.ParseCertificate(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tlsCertificate = &tls.Certificate{
|
||||
Certificate: [][]byte{raw, c.ca.Raw},
|
||||
PrivateKey: c.privateKey,
|
||||
Leaf: x509c,
|
||||
}
|
||||
|
||||
c.certsStorage.Set(key, tlsCertificate)
|
||||
return tlsCertificate, nil
|
||||
}
|
||||
|
||||
// GenerateAndSave generate CA private key and CA certificate and dump them to file
|
||||
func GenerateAndSave(caPath string, caKeyPath string) error {
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(time.Now().Unix()),
|
||||
Subject: pkix.Name{
|
||||
Country: []string{"US"},
|
||||
CommonName: "Clash Root CA",
|
||||
Organization: []string{"Clash Trust Services"},
|
||||
},
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
NotBefore: time.Now().Add(-(time.Hour * 24 * 60)),
|
||||
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 25),
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: true,
|
||||
}
|
||||
|
||||
caRaw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, privateKey.Public(), privateKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
caOut, err := os.OpenFile(caPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func(caOut *os.File) {
|
||||
_ = caOut.Close()
|
||||
}(caOut)
|
||||
|
||||
if err = pem.Encode(caOut, &pem.Block{Type: "CERTIFICATE", Bytes: caRaw}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
caKeyOut, err := os.OpenFile(caKeyPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func(caKeyOut *os.File) {
|
||||
_ = caKeyOut.Close()
|
||||
}(caKeyOut)
|
||||
|
||||
if err = pem.Encode(caKeyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasDnsNames(dnsNames []string, hostname string) bool {
|
||||
for _, name := range dnsNames {
|
||||
if name == hostname {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
@ -1,104 +0,0 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCert(t *testing.T) {
|
||||
ca, privateKey, err := NewAuthority("Clash ca", "Clash", 24*time.Hour)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, ca)
|
||||
assert.NotNil(t, privateKey)
|
||||
|
||||
c, err := NewConfig(ca, privateKey)
|
||||
assert.Nil(t, err)
|
||||
|
||||
c.SetValidity(20 * time.Hour)
|
||||
c.SetOrganization("Test Organization")
|
||||
|
||||
conf := c.NewTLSConfigForHost("example.org")
|
||||
assert.Equal(t, []string{"http/1.1"}, conf.NextProtos)
|
||||
assert.True(t, conf.InsecureSkipVerify)
|
||||
|
||||
// Test generating a certificate
|
||||
clientHello := &tls.ClientHelloInfo{
|
||||
ServerName: "example.org",
|
||||
}
|
||||
tlsCert, err := conf.GetCertificate(clientHello)
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, tlsCert)
|
||||
|
||||
// Assert certificate details
|
||||
x509c := tlsCert.Leaf
|
||||
assert.Equal(t, "example.org", x509c.Subject.CommonName)
|
||||
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
||||
assert.Nil(t, x509c.VerifyHostname("abc.example.org"))
|
||||
assert.Equal(t, []string{"Test Organization"}, x509c.Subject.Organization)
|
||||
assert.NotNil(t, x509c.SubjectKeyId)
|
||||
assert.True(t, x509c.BasicConstraintsValid)
|
||||
assert.True(t, x509c.KeyUsage&x509.KeyUsageKeyEncipherment == x509.KeyUsageKeyEncipherment)
|
||||
assert.True(t, x509c.KeyUsage&x509.KeyUsageDigitalSignature == x509.KeyUsageDigitalSignature)
|
||||
assert.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, x509c.ExtKeyUsage)
|
||||
assert.Equal(t, []string{"example.org", "*.example.org"}, x509c.DNSNames)
|
||||
assert.True(t, x509c.NotBefore.Before(time.Now().Add(-2*time.Hour)))
|
||||
assert.True(t, x509c.NotAfter.After(time.Now().Add(2*time.Hour)))
|
||||
|
||||
// Check that certificate is cached
|
||||
tlsCert2, err := c.GetOrCreateCert("abc.example.org")
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, tlsCert == tlsCert2)
|
||||
|
||||
// Check that certificate is new
|
||||
_, _ = c.GetOrCreateCert("a.b.c.d.e.f.g.h.i.j.example.org")
|
||||
tlsCert3, err := c.GetOrCreateCert("m.k.l.example.org")
|
||||
x509c = tlsCert3.Leaf
|
||||
assert.Nil(t, err)
|
||||
assert.False(t, tlsCert == tlsCert3)
|
||||
assert.Equal(t, []string{"example.org", "*.example.org", "*.j.example.org", "*.i.j.example.org", "*.h.i.j.example.org", "*.g.h.i.j.example.org", "*.f.g.h.i.j.example.org", "*.e.f.g.h.i.j.example.org", "*.d.e.f.g.h.i.j.example.org", "*.c.d.e.f.g.h.i.j.example.org", "*.b.c.d.e.f.g.h.i.j.example.org", "*.l.example.org", "*.k.l.example.org"}, x509c.DNSNames)
|
||||
|
||||
// Check that certificate is cached
|
||||
tlsCert4, err := c.GetOrCreateCert("xyz.example.org")
|
||||
x509c = tlsCert4.Leaf
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, tlsCert3 == tlsCert4)
|
||||
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
||||
assert.Nil(t, x509c.VerifyHostname("jkf.example.org"))
|
||||
assert.Nil(t, x509c.VerifyHostname("n.j.example.org"))
|
||||
assert.Nil(t, x509c.VerifyHostname("c.i.j.example.org"))
|
||||
assert.Nil(t, x509c.VerifyHostname("m.l.example.org"))
|
||||
assert.Error(t, x509c.VerifyHostname("m.l.jkf.example.org"))
|
||||
|
||||
// Check the certificate for an IP
|
||||
tlsCertForIP, err := c.GetOrCreateCert("192.168.0.1")
|
||||
x509c = tlsCertForIP.Leaf
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 1, len(x509c.IPAddresses))
|
||||
assert.True(t, net.ParseIP("192.168.0.1").Equal(x509c.IPAddresses[0]))
|
||||
|
||||
// Check that certificate is cached
|
||||
tlsCertForIP2, err := c.GetOrCreateCert("192.168.0.1")
|
||||
x509c = tlsCertForIP2.Leaf
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, tlsCertForIP == tlsCertForIP2)
|
||||
assert.Nil(t, x509c.VerifyHostname("192.168.0.1"))
|
||||
}
|
||||
|
||||
func TestGenerateAndSave(t *testing.T) {
|
||||
caPath := "ca.crt"
|
||||
caKeyPath := "ca.key"
|
||||
|
||||
err := GenerateAndSave(caPath, caKeyPath)
|
||||
|
||||
assert.Nil(t, err)
|
||||
|
||||
_ = os.Remove(caPath)
|
||||
_ = os.Remove(caKeyPath)
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
|
||||
"github.com/Dreamacro/clash/component/trie"
|
||||
)
|
||||
|
||||
// DomainTrieCertsStorage cache wildcard certificates
|
||||
type DomainTrieCertsStorage struct {
|
||||
certsCache *trie.DomainTrie[*tls.Certificate]
|
||||
}
|
||||
|
||||
// Get gets the certificate from the storage
|
||||
func (c *DomainTrieCertsStorage) Get(key string) (*tls.Certificate, bool) {
|
||||
ca := c.certsCache.Search(key)
|
||||
if ca == nil {
|
||||
return nil, false
|
||||
}
|
||||
return ca.Data, true
|
||||
}
|
||||
|
||||
// Set saves the certificate to the storage
|
||||
func (c *DomainTrieCertsStorage) Set(key string, cert *tls.Certificate) {
|
||||
_ = c.certsCache.Insert(key, cert)
|
||||
}
|
||||
|
||||
func NewDomainTrieCertsStorage() *DomainTrieCertsStorage {
|
||||
return &DomainTrieCertsStorage{
|
||||
certsCache: trie.New[*tls.Certificate](),
|
||||
}
|
||||
}
|
@ -15,7 +15,7 @@ func ExecCmd(cmdStr string) (string, error) {
|
||||
} else {
|
||||
cmd = exec.Command(args[0], args[1:]...)
|
||||
}
|
||||
|
||||
prepareBackgroundCommand(cmd)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||
|
10
common/cmd/cmd_other.go
Normal file
10
common/cmd/cmd_other.go
Normal file
@ -0,0 +1,10 @@
|
||||
//go:build !windows
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||
}
|
12
common/cmd/cmd_windows.go
Normal file
12
common/cmd/cmd_windows.go
Normal file
@ -0,0 +1,12 @@
|
||||
//go:build windows
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
||||
}
|
56
common/collections/stack.go
Normal file
56
common/collections/stack.go
Normal file
@ -0,0 +1,56 @@
|
||||
package collections
|
||||
|
||||
import "sync"
|
||||
|
||||
type (
|
||||
stack struct {
|
||||
top *node
|
||||
length int
|
||||
lock *sync.RWMutex
|
||||
}
|
||||
|
||||
node struct {
|
||||
value interface{}
|
||||
prev *node
|
||||
}
|
||||
)
|
||||
|
||||
// NewStack Create a new stack
|
||||
func NewStack() *stack {
|
||||
return &stack{nil, 0, &sync.RWMutex{}}
|
||||
}
|
||||
|
||||
// Len Return the number of items in the stack
|
||||
func (this *stack) Len() int {
|
||||
return this.length
|
||||
}
|
||||
|
||||
// Peek View the top item on the stack
|
||||
func (this *stack) Peek() interface{} {
|
||||
if this.length == 0 {
|
||||
return nil
|
||||
}
|
||||
return this.top.value
|
||||
}
|
||||
|
||||
// Pop the top item of the stack and return it
|
||||
func (this *stack) Pop() interface{} {
|
||||
this.lock.Lock()
|
||||
defer this.lock.Unlock()
|
||||
if this.length == 0 {
|
||||
return nil
|
||||
}
|
||||
n := this.top
|
||||
this.top = n.prev
|
||||
this.length--
|
||||
return n.value
|
||||
}
|
||||
|
||||
// Push a value onto the top of the stack
|
||||
func (this *stack) Push(value interface{}) {
|
||||
this.lock.Lock()
|
||||
defer this.lock.Unlock()
|
||||
n := &node{value, this.top}
|
||||
this.top = n
|
||||
this.length++
|
||||
}
|
450
common/convert/converter.go
Normal file
450
common/convert/converter.go
Normal file
@ -0,0 +1,450 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var enc = base64.StdEncoding
|
||||
|
||||
func DecodeBase64(buf []byte) ([]byte, error) {
|
||||
dBuf := make([]byte, enc.DecodedLen(len(buf)))
|
||||
n, err := enc.Decode(dBuf, buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dBuf[:n], nil
|
||||
}
|
||||
|
||||
// DecodeBase64StringToString decode base64 string to string
|
||||
func DecodeBase64StringToString(s string) (string, error) {
|
||||
dBuf, err := enc.DecodeString(s)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(dBuf), nil
|
||||
}
|
||||
|
||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
data, err := DecodeBase64(buf)
|
||||
if err != nil {
|
||||
data = buf
|
||||
}
|
||||
|
||||
arr := strings.Split(string(data), "\n")
|
||||
|
||||
proxies := make([]map[string]any, 0, len(arr))
|
||||
names := make(map[string]int, 200)
|
||||
|
||||
for _, line := range arr {
|
||||
line = strings.TrimRight(line, " \r")
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
scheme, body, found := strings.Cut(line, "://")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
|
||||
scheme = strings.ToLower(scheme)
|
||||
switch scheme {
|
||||
case "hysteria":
|
||||
urlHysteria, err := url.Parse(line)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
query := urlHysteria.Query()
|
||||
name := uniqueName(names, urlHysteria.Fragment)
|
||||
hysteria := make(map[string]any, 20)
|
||||
|
||||
hysteria["name"] = name
|
||||
hysteria["type"] = scheme
|
||||
hysteria["server"] = urlHysteria.Hostname()
|
||||
hysteria["port"] = urlHysteria.Port()
|
||||
hysteria["sni"] = query.Get("peer")
|
||||
hysteria["obfs"] = query.Get("obfs")
|
||||
hysteria["alpn"] = query.Get("alpn")
|
||||
hysteria["auth_str"] = query.Get("auth")
|
||||
hysteria["protocol"] = query.Get("protocol")
|
||||
hysteria["down_mbps"], _ = strconv.Atoi(query.Get("downmbps"))
|
||||
hysteria["up_mbps"], _ = strconv.Atoi(query.Get("upmbps"))
|
||||
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||
|
||||
proxies = append(proxies, hysteria)
|
||||
|
||||
case "trojan":
|
||||
urlTrojan, err := url.Parse(line)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
query := urlTrojan.Query()
|
||||
|
||||
name := uniqueName(names, urlTrojan.Fragment)
|
||||
trojan := make(map[string]any, 20)
|
||||
|
||||
trojan["name"] = name
|
||||
trojan["type"] = scheme
|
||||
trojan["server"] = urlTrojan.Hostname()
|
||||
trojan["port"] = urlTrojan.Port()
|
||||
trojan["password"] = urlTrojan.User.Username()
|
||||
trojan["udp"] = true
|
||||
trojan["skip-cert-verify"] = false
|
||||
|
||||
sni := query.Get("sni")
|
||||
if sni != "" {
|
||||
trojan["sni"] = sni
|
||||
}
|
||||
|
||||
network := strings.ToLower(query.Get("type"))
|
||||
if network != "" {
|
||||
trojan["network"] = network
|
||||
}
|
||||
|
||||
switch network {
|
||||
case "ws":
|
||||
headers := make(map[string]any)
|
||||
wsOpts := make(map[string]any)
|
||||
|
||||
// headers["Host"] = RandHost()
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
|
||||
wsOpts["path"] = query.Get("path")
|
||||
wsOpts["headers"] = headers
|
||||
|
||||
trojan["ws-opts"] = wsOpts
|
||||
|
||||
case "grpc":
|
||||
grpcOpts := make(map[string]any)
|
||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||
trojan["grpc-opts"] = grpcOpts
|
||||
}
|
||||
|
||||
proxies = append(proxies, trojan)
|
||||
|
||||
case "vless":
|
||||
urlVless, err := url.Parse(line)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
query := urlVless.Query()
|
||||
|
||||
name := uniqueName(names, urlVless.Fragment)
|
||||
vless := make(map[string]any, 20)
|
||||
|
||||
vless["name"] = name
|
||||
vless["type"] = scheme
|
||||
vless["server"] = urlVless.Hostname()
|
||||
vless["port"] = urlVless.Port()
|
||||
vless["uuid"] = urlVless.User.Username()
|
||||
vless["udp"] = true
|
||||
vless["skip-cert-verify"] = false
|
||||
|
||||
sni := query.Get("sni")
|
||||
if sni != "" {
|
||||
vless["servername"] = sni
|
||||
}
|
||||
|
||||
flow := strings.ToLower(query.Get("flow"))
|
||||
if flow != "" {
|
||||
vless["flow"] = flow
|
||||
}
|
||||
|
||||
network := strings.ToLower(query.Get("type"))
|
||||
if network != "" {
|
||||
fakeType := strings.ToLower(query.Get("headerType"))
|
||||
if network == "tcp" && fakeType == "http" {
|
||||
network = "http"
|
||||
}
|
||||
if network == "http" {
|
||||
network = "h2"
|
||||
}
|
||||
vless["network"] = network
|
||||
}
|
||||
|
||||
switch network {
|
||||
case "http":
|
||||
headers := make(map[string]any)
|
||||
httpOpts := make(map[string]any)
|
||||
|
||||
if query.Get("method") != "" {
|
||||
httpOpts["method"] = query.Get("method")
|
||||
}
|
||||
if query.Get("path") != "" {
|
||||
httpOpts["path"] = query.Get("path")
|
||||
}
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
httpOpts["headers"] = headers
|
||||
|
||||
vless["http-opts"] = httpOpts
|
||||
|
||||
case "h2":
|
||||
headers := make(map[string]any)
|
||||
h2Opts := make(map[string]any)
|
||||
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
h2Opts["path"] = query.Get("path")
|
||||
h2Opts["headers"] = headers
|
||||
|
||||
vless["h2-opts"] = h2Opts
|
||||
|
||||
case "ws":
|
||||
headers := make(map[string]any)
|
||||
wsOpts := make(map[string]any)
|
||||
|
||||
// headers["Host"] = RandHost()
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
wsOpts["path"] = query.Get("path")
|
||||
wsOpts["headers"] = headers
|
||||
|
||||
vless["ws-opts"] = wsOpts
|
||||
|
||||
case "grpc":
|
||||
grpcOpts := make(map[string]any)
|
||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||
vless["grpc-opts"] = grpcOpts
|
||||
}
|
||||
|
||||
proxies = append(proxies, vless)
|
||||
|
||||
case "vmess":
|
||||
dcBuf, err := enc.DecodeString(body)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
jsonDc := json.NewDecoder(bytes.NewReader(dcBuf))
|
||||
values := make(map[string]any, 20)
|
||||
|
||||
if jsonDc.Decode(&values) != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
name := uniqueName(names, values["ps"].(string))
|
||||
vmess := make(map[string]any, 20)
|
||||
|
||||
vmess["name"] = name
|
||||
vmess["type"] = scheme
|
||||
vmess["server"] = values["add"]
|
||||
vmess["port"] = values["port"]
|
||||
vmess["uuid"] = values["id"]
|
||||
vmess["alterId"] = values["aid"]
|
||||
vmess["cipher"] = "auto"
|
||||
vmess["udp"] = true
|
||||
vmess["skip-cert-verify"] = false
|
||||
|
||||
sni := values["sni"]
|
||||
if sni != "" {
|
||||
vmess["sni"] = sni
|
||||
}
|
||||
|
||||
host := values["host"]
|
||||
network := strings.ToLower(values["net"].(string))
|
||||
|
||||
vmess["network"] = network
|
||||
|
||||
tls := strings.ToLower(values["tls"].(string))
|
||||
if tls != "" && tls != "0" && tls != "null" {
|
||||
if host != nil {
|
||||
vmess["servername"] = host
|
||||
}
|
||||
vmess["tls"] = true
|
||||
}
|
||||
|
||||
switch network {
|
||||
case "http":
|
||||
headers := make(map[string]any)
|
||||
httpOpts := make(map[string]any)
|
||||
|
||||
// headers["Host"] = RandHost()
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
httpOpts["method"] = values["method"]
|
||||
httpOpts["path"] = values["path"]
|
||||
httpOpts["headers"] = headers
|
||||
|
||||
vmess["http-opts"] = httpOpts
|
||||
|
||||
case "h2":
|
||||
headers := make(map[string]any)
|
||||
h2Opts := make(map[string]any)
|
||||
|
||||
// headers["Host"] = RandHost()
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
h2Opts["path"] = values["path"]
|
||||
h2Opts["headers"] = headers
|
||||
|
||||
vmess["h2-opts"] = h2Opts
|
||||
|
||||
case "ws":
|
||||
headers := make(map[string]any)
|
||||
wsOpts := make(map[string]any)
|
||||
|
||||
headers["Host"] = RandHost()
|
||||
headers["User-Agent"] = RandUserAgent()
|
||||
|
||||
if values["path"] != nil {
|
||||
wsOpts["path"] = values["path"]
|
||||
}
|
||||
wsOpts["headers"] = headers
|
||||
|
||||
vmess["ws-opts"] = wsOpts
|
||||
|
||||
case "grpc":
|
||||
grpcOpts := make(map[string]any)
|
||||
grpcOpts["grpc-service-name"] = values["path"]
|
||||
vmess["grpc-opts"] = grpcOpts
|
||||
}
|
||||
|
||||
proxies = append(proxies, vmess)
|
||||
|
||||
case "ss":
|
||||
urlSS, err := url.Parse(line)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
name := uniqueName(names, urlSS.Fragment)
|
||||
port := urlSS.Port()
|
||||
|
||||
if port == "" {
|
||||
dcBuf, err := enc.DecodeString(urlSS.Host)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
urlSS, err = url.Parse("ss://" + string(dcBuf))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
cipher = urlSS.User.Username()
|
||||
password string
|
||||
)
|
||||
|
||||
if password, found = urlSS.User.Password(); !found {
|
||||
dcBuf, err := enc.DecodeString(cipher)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
ss := make(map[string]any, 20)
|
||||
|
||||
ss["name"] = name
|
||||
ss["type"] = scheme
|
||||
ss["server"] = urlSS.Hostname()
|
||||
ss["port"] = urlSS.Port()
|
||||
ss["cipher"] = cipher
|
||||
ss["password"] = password
|
||||
ss["udp"] = true
|
||||
|
||||
proxies = append(proxies, ss)
|
||||
case "ssr":
|
||||
dcBuf, err := enc.DecodeString(body)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// ssr://host:port:protocol:method:obfs:urlsafebase64pass/?obfsparam=urlsafebase64&protoparam=&remarks=urlsafebase64&group=urlsafebase64&udpport=0&uot=1
|
||||
|
||||
before, after, ok := strings.Cut(string(dcBuf), "/?")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
beforeArr := strings.Split(before, ":")
|
||||
|
||||
if len(beforeArr) != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
host := beforeArr[0]
|
||||
port := beforeArr[1]
|
||||
protocol := beforeArr[2]
|
||||
method := beforeArr[3]
|
||||
obfs := beforeArr[4]
|
||||
password := decodeUrlSafe(urlSafe(beforeArr[5]))
|
||||
|
||||
query, err := url.ParseQuery(urlSafe(after))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
remarks := decodeUrlSafe(query.Get("remarks"))
|
||||
name := uniqueName(names, remarks)
|
||||
|
||||
obfsParam := decodeUrlSafe(query.Get("obfsparam"))
|
||||
protocolParam := query.Get("protoparam")
|
||||
|
||||
ssr := make(map[string]any, 20)
|
||||
|
||||
ssr["name"] = name
|
||||
ssr["type"] = scheme
|
||||
ssr["server"] = host
|
||||
ssr["port"] = port
|
||||
ssr["cipher"] = method
|
||||
ssr["password"] = password
|
||||
ssr["obfs"] = obfs
|
||||
ssr["protocol"] = protocol
|
||||
ssr["udp"] = true
|
||||
|
||||
if obfsParam != "" {
|
||||
ssr["obfs-param"] = obfsParam
|
||||
}
|
||||
|
||||
if protocolParam != "" {
|
||||
ssr["protocol-param"] = protocolParam
|
||||
}
|
||||
|
||||
proxies = append(proxies, ssr)
|
||||
}
|
||||
}
|
||||
|
||||
if len(proxies) == 0 {
|
||||
return nil, fmt.Errorf("convert v2ray subscribe error: format invalid")
|
||||
}
|
||||
|
||||
return proxies, nil
|
||||
}
|
||||
|
||||
func urlSafe(data string) string {
|
||||
return strings.ReplaceAll(strings.ReplaceAll(data, "+", "-"), "/", "_")
|
||||
}
|
||||
|
||||
func decodeUrlSafe(data string) string {
|
||||
dcBuf, err := base64.URLEncoding.DecodeString(data)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(dcBuf)
|
||||
}
|
||||
|
||||
func uniqueName(names map[string]int, name string) string {
|
||||
if index, ok := names[name]; ok {
|
||||
index++
|
||||
names[name] = index
|
||||
name = fmt.Sprintf("%s-%02d", name, index)
|
||||
} else {
|
||||
index = 0
|
||||
names[name] = index
|
||||
}
|
||||
return name
|
||||
}
|
316
common/convert/util.go
Normal file
316
common/convert/util.go
Normal file
@ -0,0 +1,316 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gofrs/uuid"
|
||||
)
|
||||
|
||||
var hostsSuffix = []string{
|
||||
"-cdn.aliyuncs.com",
|
||||
".alicdn.com",
|
||||
".pan.baidu.com",
|
||||
".tbcache.com",
|
||||
".aliyuncdn.com",
|
||||
".vod.miguvideo.com",
|
||||
".cibntv.net",
|
||||
".myqcloud.com",
|
||||
".smtcdns.com",
|
||||
".alikunlun.com",
|
||||
".smtcdns.net",
|
||||
".apcdns.net",
|
||||
".cdn-go.cn",
|
||||
".cdntip.com",
|
||||
".cdntips.com",
|
||||
".alidayu.com",
|
||||
".alidns.com",
|
||||
".cdngslb.com",
|
||||
".mxhichina.com",
|
||||
".alibabadns.com",
|
||||
}
|
||||
|
||||
var userAgents = []string{
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; Moto C Build/NRD90M.059) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J120M Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; Moto G (5) Build/NPPS25.137-93-14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 5.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0; CAM-L03 Build/HUAWEICAM-L03) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
||||
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Datanyze; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J111M Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J700M Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Slackware/Chrome/12.0.742.100 Safari/534.30",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 8.0.0; WAS-LX3 Build/HUAWEIWAS-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.1805 Safari/537.36 MVisionPlayer/1.0.0.0",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX3 Build/HUAWEITRT-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1610 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 4.4.2; de-de; SAMSUNG GT-I9195 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 8.0.0; ANE-LX3 Build/HUAWEIANE-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; U; Linux i586; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J500M Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1606 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.1; vivo 1716 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0; MYA-L22 Build/HUAWEIMYA-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 5.1; A1601 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX2 Build/HUAWEITRT-LX2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
||||
"Mozilla/5.0 (Linux; Android 6.0; CAM-L21 Build/HUAWEICAM-L21; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.3 Safari/534.24",
|
||||
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4X Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 4.4.2; SM-G7102 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 5.1; HUAWEI CUN-L22 Build/HUAWEICUN-L22; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 5.1.1; A37fw Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-J730GM Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi Note 5A Build/N2G47H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Unknown; Linux) AppleWebKit/538.1 (KHTML, like Gecko) Chrome/v1.0.0 Safari/538.1",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; BLL-L22 Build/HUAWEIBLL-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.0; SM-J710F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.1.1; CPH1723 Build/N6F26Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3 Build/HUAWEIFIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 7.1; Mi A1 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 MVisionPlayer/1.0.0.0",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 5.1; A37f Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; CPH1607 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; vivo 1603 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4A Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.116 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1713 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
||||
}
|
||||
|
||||
var (
|
||||
hostsLen = len(hostsSuffix)
|
||||
uaLen = len(userAgents)
|
||||
)
|
||||
|
||||
func RandHost() string {
|
||||
id, _ := uuid.NewV4()
|
||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
||||
base = strings.ReplaceAll(base, "-", "")
|
||||
base = strings.ReplaceAll(base, "_", "")
|
||||
buf := []byte(base)
|
||||
prefix := string(buf[:3]) + "---"
|
||||
prefix += string(buf[6:8]) + "-"
|
||||
prefix += string(buf[len(buf)-8:])
|
||||
|
||||
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
||||
}
|
||||
|
||||
func RandUserAgent() string {
|
||||
return userAgents[rand.Intn(uaLen)]
|
||||
}
|
||||
|
||||
func SetUserAgent(header http.Header) {
|
||||
if header.Get("User-Agent") != "" {
|
||||
return
|
||||
}
|
||||
userAgent := RandUserAgent()
|
||||
header.Set("User-Agent", userAgent)
|
||||
}
|
@ -12,28 +12,19 @@ import (
|
||||
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())
|
||||
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())
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
46
common/net/tcpip.go
Normal file
46
common/net/tcpip.go
Normal file
@ -0,0 +1,46 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func SplitNetworkType(s string) (string, string, error) {
|
||||
var (
|
||||
shecme string
|
||||
hostPort string
|
||||
)
|
||||
result := strings.Split(s, "://")
|
||||
if len(result) == 2 {
|
||||
shecme = result[0]
|
||||
hostPort = result[1]
|
||||
} else if len(result) == 1 {
|
||||
hostPort = result[0]
|
||||
} else {
|
||||
return "", "", fmt.Errorf("tcp/udp style error")
|
||||
}
|
||||
|
||||
if len(shecme) == 0 {
|
||||
shecme = "udp"
|
||||
}
|
||||
|
||||
if shecme != "tcp" && shecme != "udp" {
|
||||
return "", "", fmt.Errorf("scheme should be tcp:// or udp://")
|
||||
} else {
|
||||
return shecme, hostPort, nil
|
||||
}
|
||||
}
|
||||
|
||||
func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
||||
temp := s
|
||||
hasPort = true
|
||||
|
||||
if !strings.Contains(s, ":") && !strings.Contains(s, "]:") {
|
||||
temp += ":0"
|
||||
hasPort = false
|
||||
}
|
||||
|
||||
host, port, err = net.SplitHostPort(temp)
|
||||
return
|
||||
}
|
@ -6,10 +6,16 @@ import (
|
||||
"errors"
|
||||
"math/bits"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
)
|
||||
|
||||
var defaultAllocator = NewAllocator()
|
||||
|
||||
func init() {
|
||||
buf.DefaultAllocator = defaultAllocator
|
||||
}
|
||||
|
||||
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||
type Allocator struct {
|
||||
buffers []sync.Pool
|
||||
@ -52,8 +58,8 @@ func (alloc *Allocator) Put(buf []byte) error {
|
||||
return errors.New("allocator Put() incorrect buffer size")
|
||||
}
|
||||
|
||||
//lint:ignore SA6002 ignore temporarily
|
||||
//nolint
|
||||
//lint:ignore SA6002 ignore temporarily
|
||||
alloc.buffers[bits].Put(buf)
|
||||
return nil
|
||||
}
|
||||
|
@ -25,7 +25,6 @@ type Result[T any] struct {
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
@ -31,7 +31,7 @@ func NewDecoder(option Option) *Decoder {
|
||||
// Decode transform a map[string]any to a struct
|
||||
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||
return fmt.Errorf("Decode must recive a ptr struct")
|
||||
return fmt.Errorf("decode must recive a ptr struct")
|
||||
}
|
||||
t := reflect.TypeOf(dst).Elem()
|
||||
v := reflect.ValueOf(dst).Elem()
|
||||
@ -301,7 +301,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
||||
field reflect.StructField
|
||||
val reflect.Value
|
||||
}
|
||||
fields := []field{}
|
||||
var fields []field
|
||||
for len(structs) > 0 {
|
||||
structVal := structs[0]
|
||||
structs = structs[1:]
|
||||
|
@ -137,45 +137,3 @@ func TestStructure_Nest(t *testing.T) {
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, s.BazOptional, goal)
|
||||
}
|
||||
|
||||
func TestStructure_SliceNilValue(t *testing.T) {
|
||||
rawMap := map[string]any{
|
||||
"foo": 1,
|
||||
"bar": []any{"bar", nil},
|
||||
}
|
||||
|
||||
goal := &BazSlice{
|
||||
Foo: 1,
|
||||
Bar: []string{"bar", ""},
|
||||
}
|
||||
|
||||
s := &BazSlice{}
|
||||
err := weakTypeDecoder.Decode(rawMap, s)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, goal.Bar, s.Bar)
|
||||
|
||||
s = &BazSlice{}
|
||||
err = decoder.Decode(rawMap, s)
|
||||
assert.NotNil(t, err)
|
||||
}
|
||||
|
||||
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
||||
rawMap := map[string]any{
|
||||
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
||||
}
|
||||
|
||||
s := &struct {
|
||||
Bar []map[string]any `test:"bar"`
|
||||
}{}
|
||||
|
||||
err := decoder.Decode(rawMap, s)
|
||||
assert.Nil(t, err)
|
||||
assert.Nil(t, s.Bar[1])
|
||||
|
||||
ss := &struct {
|
||||
Bar []Baz `test:"bar"`
|
||||
}{}
|
||||
|
||||
err = decoder.Decode(rawMap, ss)
|
||||
assert.NotNil(t, err)
|
||||
}
|
||||
|
44
common/utils/range.go
Normal file
44
common/utils/range.go
Normal file
@ -0,0 +1,44 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
type Range[T constraints.Ordered] struct {
|
||||
start T
|
||||
end T
|
||||
}
|
||||
|
||||
func NewRange[T constraints.Ordered](start, end T) *Range[T] {
|
||||
if start > end {
|
||||
return &Range[T]{
|
||||
start: end,
|
||||
end: start,
|
||||
}
|
||||
}
|
||||
|
||||
return &Range[T]{
|
||||
start: start,
|
||||
end: end,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Range[T]) Contains(t T) bool {
|
||||
return t >= r.start && t <= r.end
|
||||
}
|
||||
|
||||
func (r *Range[T]) LeftContains(t T) bool {
|
||||
return t >= r.start && t < r.end
|
||||
}
|
||||
|
||||
func (r *Range[T]) RightContains(t T) bool {
|
||||
return t > r.start && t <= r.end
|
||||
}
|
||||
|
||||
func (r *Range[T]) Start() T {
|
||||
return r.start
|
||||
}
|
||||
|
||||
func (r *Range[T]) End() T {
|
||||
return r.end
|
||||
}
|
16
common/utils/uuid.go
Normal file
16
common/utils/uuid.go
Normal file
@ -0,0 +1,16 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/gofrs/uuid"
|
||||
)
|
||||
|
||||
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
||||
|
||||
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||
func UUIDMap(str string) (uuid.UUID, error) {
|
||||
u, err := uuid.FromString(str)
|
||||
if err != nil {
|
||||
return uuid.NewV5(uuidNamespace, str), nil
|
||||
}
|
||||
return u, nil
|
||||
}
|
75
common/utils/uuid_test.go
Normal file
75
common/utils/uuid_test.go
Normal file
@ -0,0 +1,75 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/gofrs/uuid"
|
||||
)
|
||||
|
||||
func TestUUIDMap(t *testing.T) {
|
||||
type args struct {
|
||||
str string
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want uuid.UUID
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "uuid-test-1",
|
||||
args: args{
|
||||
str: "82410302-039e-41b6-98b0-d964084b4170",
|
||||
},
|
||||
want: uuid.FromStringOrNil("82410302-039e-41b6-98b0-d964084b4170"),
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "uuid-test-2",
|
||||
args: args{
|
||||
str: "88c502e6-d7eb-4c8e-8259-94cb13d83c77",
|
||||
},
|
||||
want: uuid.FromStringOrNil("88c502e6-d7eb-4c8e-8259-94cb13d83c77"),
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "uuid-map-1",
|
||||
args: args{
|
||||
str: "123456",
|
||||
},
|
||||
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
|
||||
wantErr: false,
|
||||
},
|
||||
// GENERATED BY 'xray uuid -i'
|
||||
{
|
||||
name: "uuid-map-2",
|
||||
args: args{
|
||||
str: "a9dk23bz0",
|
||||
},
|
||||
want: uuid.FromStringOrNil("c91481b6-fc0f-5d9e-b166-5ddf07b9c3c5"),
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "uuid-map-2",
|
||||
args: args{
|
||||
str: "中文123",
|
||||
},
|
||||
want: uuid.FromStringOrNil("145c544c-2229-59e5-8dbb-3f33b7610d26"),
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := UUIDMap(tt.args.str)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("UUIDMap() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("UUIDMap() got = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/common/nnip"
|
||||
"github.com/Dreamacro/clash/component/iface"
|
||||
|
||||
"github.com/insomniacslk/dhcp/dhcpv4"
|
||||
)
|
||||
|
||||
|
@ -6,7 +6,6 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/Dreamacro/clash/component/iface"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
|
@ -3,12 +3,22 @@ package dialer
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
)
|
||||
|
||||
var (
|
||||
dialMux sync.Mutex
|
||||
actualSingleDialContext = singleDialContext
|
||||
actualDualStackDialContext = dualStackDialContext
|
||||
tcpConcurrent = false
|
||||
DisableIPv6 = false
|
||||
)
|
||||
|
||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||
opt := &option{
|
||||
interfaceName: DefaultInterface.Load(),
|
||||
@ -25,33 +35,9 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
||||
|
||||
switch network {
|
||||
case "tcp4", "tcp6", "udp4", "udp6":
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ip netip.Addr
|
||||
switch network {
|
||||
case "tcp4", "udp4":
|
||||
if !opt.direct {
|
||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||
} else {
|
||||
ip, err = resolver.ResolveIPv4(host)
|
||||
}
|
||||
default:
|
||||
if !opt.direct {
|
||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||
} else {
|
||||
ip, err = resolver.ResolveIPv6(host)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dialContext(ctx, network, ip, port, opt)
|
||||
return actualSingleDialContext(ctx, network, address, opt)
|
||||
case "tcp", "udp":
|
||||
return dualStackDialContext(ctx, network, address, opt)
|
||||
return actualDualStackDialContext(ctx, network, address, opt)
|
||||
default:
|
||||
return nil, errors.New("network invalid")
|
||||
}
|
||||
@ -89,6 +75,24 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
||||
return lc.ListenPacket(ctx, network, address)
|
||||
}
|
||||
|
||||
func SetDial(concurrent bool) {
|
||||
dialMux.Lock()
|
||||
tcpConcurrent = concurrent
|
||||
if concurrent {
|
||||
actualSingleDialContext = concurrentSingleDialContext
|
||||
actualDualStackDialContext = concurrentDualStackDialContext
|
||||
} else {
|
||||
actualSingleDialContext = singleDialContext
|
||||
actualDualStackDialContext = dualStackDialContext
|
||||
}
|
||||
|
||||
dialMux.Unlock()
|
||||
}
|
||||
|
||||
func GetDial() bool {
|
||||
return tcpConcurrent
|
||||
}
|
||||
|
||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||
dialer := &net.Dialer{}
|
||||
if opt.interfaceName != "" {
|
||||
@ -100,6 +104,10 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||
}
|
||||
|
||||
if DisableIPv6 && destination.Is6() {
|
||||
return nil, fmt.Errorf("IPv6 is diabled, dialer cancel")
|
||||
}
|
||||
|
||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||
}
|
||||
|
||||
@ -183,3 +191,130 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
||||
|
||||
return nil, errors.New("never touched")
|
||||
}
|
||||
|
||||
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ips []netip.Addr
|
||||
|
||||
if opt.direct {
|
||||
ips, err = resolver.ResolveAllIP(host)
|
||||
} else {
|
||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||
}
|
||||
|
||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
|
||||
type dialResult struct {
|
||||
ip netip.Addr
|
||||
net.Conn
|
||||
error
|
||||
resolved bool
|
||||
}
|
||||
|
||||
results := make(chan dialResult)
|
||||
|
||||
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
||||
result := dialResult{ip: ip}
|
||||
|
||||
defer func() {
|
||||
select {
|
||||
case results <- result:
|
||||
case <-returned:
|
||||
if result.Conn != nil {
|
||||
result.Conn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
v := "4"
|
||||
if ip.Is6() {
|
||||
v = "6"
|
||||
}
|
||||
|
||||
result.Conn, result.error = dialContext(ctx, network+v, ip, port, opt)
|
||||
}
|
||||
|
||||
for _, ip := range ips {
|
||||
go tcpRacer(ctx, ip)
|
||||
}
|
||||
|
||||
connCount := len(ips)
|
||||
for res := range results {
|
||||
connCount--
|
||||
if res.error == nil {
|
||||
return res.Conn, nil
|
||||
}
|
||||
|
||||
if connCount == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
||||
}
|
||||
|
||||
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ip netip.Addr
|
||||
switch network {
|
||||
case "tcp4", "udp4":
|
||||
if !opt.direct {
|
||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||
} else {
|
||||
ip, err = resolver.ResolveIPv4(host)
|
||||
}
|
||||
default:
|
||||
if !opt.direct {
|
||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||
} else {
|
||||
ip, err = resolver.ResolveIPv6(host)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dialContext(ctx, network, ip, port, opt)
|
||||
}
|
||||
|
||||
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ips []netip.Addr
|
||||
switch network {
|
||||
case "tcp4", "udp4":
|
||||
if !opt.direct {
|
||||
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
||||
} else {
|
||||
ips, err = resolver.ResolveAllIPv4(host)
|
||||
}
|
||||
default:
|
||||
if !opt.direct {
|
||||
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
||||
} else {
|
||||
ips, err = resolver.ResolveAllIPv6(host)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/component/profile/cachefile"
|
||||
"github.com/Dreamacro/clash/component/trie"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/component/geodata/router"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
@ -14,7 +15,7 @@ type loader struct {
|
||||
}
|
||||
|
||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
||||
return l.LoadGeoSiteWithAttr("geosite.dat", list)
|
||||
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
||||
}
|
||||
|
||||
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
||||
@ -29,7 +30,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
||||
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
||||
}
|
||||
|
||||
domains, err := l.LoadSite(file, list)
|
||||
domains, err := l.LoadSiteByPath(file, list)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -58,7 +59,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
||||
}
|
||||
|
||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||
return l.LoadIP("geoip.dat", country)
|
||||
return l.LoadIPByPath(C.GeoipName, country)
|
||||
}
|
||||
|
||||
var loaders map[string]func() LoaderImplementation
|
||||
|
@ -5,8 +5,10 @@ import (
|
||||
)
|
||||
|
||||
type LoaderImplementation interface {
|
||||
LoadSite(filename, list string) ([]*router.Domain, error)
|
||||
LoadIP(filename, country string) ([]*router.CIDR, error)
|
||||
LoadSiteByPath(filename, list string) ([]*router.Domain, error)
|
||||
LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error)
|
||||
LoadIPByPath(filename, country string) ([]*router.CIDR, error)
|
||||
LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error)
|
||||
}
|
||||
|
||||
type Loader interface {
|
||||
|
@ -8,7 +8,6 @@ import (
|
||||
"github.com/Dreamacro/clash/component/geodata/router"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@ -33,7 +32,7 @@ func (g GeoIPCache) Set(key string, value *router.GeoIP) {
|
||||
}
|
||||
|
||||
func (g GeoIPCache) Unmarshal(filename, code string) (*router.GeoIP, error) {
|
||||
asset := C.Path.Resolve(filename)
|
||||
asset := C.Path.GetAssetLocation(filename)
|
||||
idx := strings.ToLower(asset + ":" + code)
|
||||
if g.Has(idx) {
|
||||
return g.Get(idx), nil
|
||||
@ -98,7 +97,7 @@ func (g GeoSiteCache) Set(key string, value *router.GeoSite) {
|
||||
}
|
||||
|
||||
func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error) {
|
||||
asset := C.Path.Resolve(filename)
|
||||
asset := C.Path.GetAssetLocation(filename)
|
||||
idx := strings.ToLower(asset + ":" + code)
|
||||
if g.Has(idx) {
|
||||
return g.Get(idx), nil
|
||||
|
@ -1,6 +1,7 @@
|
||||
package memconservative
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
@ -13,7 +14,7 @@ type memConservativeLoader struct {
|
||||
geositecache GeoSiteCache
|
||||
}
|
||||
|
||||
func (m *memConservativeLoader) LoadIP(filename, country string) ([]*router.CIDR, error) {
|
||||
func (m *memConservativeLoader) LoadIPByPath(filename, country string) ([]*router.CIDR, error) {
|
||||
defer runtime.GC()
|
||||
geoip, err := m.geoipcache.Unmarshal(filename, country)
|
||||
if err != nil {
|
||||
@ -22,7 +23,11 @@ func (m *memConservativeLoader) LoadIP(filename, country string) ([]*router.CIDR
|
||||
return geoip.Cidr, nil
|
||||
}
|
||||
|
||||
func (m *memConservativeLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
|
||||
func (m *memConservativeLoader) LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error) {
|
||||
return nil, errors.New("memConservative do not support LoadIPByBytes")
|
||||
}
|
||||
|
||||
func (m *memConservativeLoader) LoadSiteByPath(filename, list string) ([]*router.Domain, error) {
|
||||
defer runtime.GC()
|
||||
geosite, err := m.geositecache.Unmarshal(filename, list)
|
||||
if err != nil {
|
||||
@ -31,6 +36,10 @@ func (m *memConservativeLoader) LoadSite(filename, list string) ([]*router.Domai
|
||||
return geosite.Domain, nil
|
||||
}
|
||||
|
||||
func (m *memConservativeLoader) LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error) {
|
||||
return nil, errors.New("memConservative do not support LoadSiteByBytes")
|
||||
}
|
||||
|
||||
func newMemConservativeLoader() geodata.LoaderImplementation {
|
||||
return &memConservativeLoader{make(map[string]*router.GeoIP), make(map[string]*router.GeoSite)}
|
||||
}
|
||||
|
@ -1,7 +1,10 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/component/geodata/strmatcher"
|
||||
@ -30,9 +33,10 @@ func domainToMatcher(domain *Domain) (strmatcher.Matcher, error) {
|
||||
|
||||
type DomainMatcher struct {
|
||||
matchers strmatcher.IndexMatcher
|
||||
not bool
|
||||
}
|
||||
|
||||
func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
|
||||
func NewMphMatcherGroup(domains []*Domain, not bool) (*DomainMatcher, error) {
|
||||
g := strmatcher.NewMphMatcherGroup()
|
||||
for _, d := range domains {
|
||||
matcherType, f := matcherTypeMap[d.Type]
|
||||
@ -47,11 +51,12 @@ func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
|
||||
g.Build()
|
||||
return &DomainMatcher{
|
||||
matchers: g,
|
||||
not: not,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewDomainMatcher new domain matcher.
|
||||
func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
||||
func NewDomainMatcher(domains []*Domain, not bool) (*DomainMatcher, error) {
|
||||
g := new(strmatcher.MatcherGroup)
|
||||
for _, d := range domains {
|
||||
m, err := domainToMatcher(d)
|
||||
@ -63,9 +68,289 @@ func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
||||
|
||||
return &DomainMatcher{
|
||||
matchers: g,
|
||||
not: not,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
||||
return len(m.matchers.Match(strings.ToLower(domain))) > 0
|
||||
isMatched := len(m.matchers.Match(strings.ToLower(domain))) > 0
|
||||
if m.not {
|
||||
isMatched = !isMatched
|
||||
}
|
||||
return isMatched
|
||||
}
|
||||
|
||||
// CIDRList is an alias of []*CIDR to provide sort.Interface.
|
||||
type CIDRList []*CIDR
|
||||
|
||||
// Len implements sort.Interface.
|
||||
func (l *CIDRList) Len() int {
|
||||
return len(*l)
|
||||
}
|
||||
|
||||
// Less implements sort.Interface.
|
||||
func (l *CIDRList) Less(i int, j int) bool {
|
||||
ci := (*l)[i]
|
||||
cj := (*l)[j]
|
||||
|
||||
if len(ci.Ip) < len(cj.Ip) {
|
||||
return true
|
||||
}
|
||||
|
||||
if len(ci.Ip) > len(cj.Ip) {
|
||||
return false
|
||||
}
|
||||
|
||||
for k := 0; k < len(ci.Ip); k++ {
|
||||
if ci.Ip[k] < cj.Ip[k] {
|
||||
return true
|
||||
}
|
||||
|
||||
if ci.Ip[k] > cj.Ip[k] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return ci.Prefix < cj.Prefix
|
||||
}
|
||||
|
||||
// Swap implements sort.Interface.
|
||||
func (l *CIDRList) Swap(i int, j int) {
|
||||
(*l)[i], (*l)[j] = (*l)[j], (*l)[i]
|
||||
}
|
||||
|
||||
type ipv6 struct {
|
||||
a uint64
|
||||
b uint64
|
||||
}
|
||||
|
||||
type GeoIPMatcher struct {
|
||||
countryCode string
|
||||
reverseMatch bool
|
||||
ip4 []uint32
|
||||
prefix4 []uint8
|
||||
ip6 []ipv6
|
||||
prefix6 []uint8
|
||||
}
|
||||
|
||||
func normalize4(ip uint32, prefix uint8) uint32 {
|
||||
return (ip >> (32 - prefix)) << (32 - prefix)
|
||||
}
|
||||
|
||||
func normalize6(ip ipv6, prefix uint8) ipv6 {
|
||||
if prefix <= 64 {
|
||||
ip.a = (ip.a >> (64 - prefix)) << (64 - prefix)
|
||||
ip.b = 0
|
||||
} else {
|
||||
ip.b = (ip.b >> (128 - prefix)) << (128 - prefix)
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) Init(cidrs []*CIDR) error {
|
||||
ip4Count := 0
|
||||
ip6Count := 0
|
||||
|
||||
for _, cidr := range cidrs {
|
||||
ip := cidr.Ip
|
||||
switch len(ip) {
|
||||
case 4:
|
||||
ip4Count++
|
||||
case 16:
|
||||
ip6Count++
|
||||
default:
|
||||
return fmt.Errorf("unexpect ip length: %d", len(ip))
|
||||
}
|
||||
}
|
||||
|
||||
cidrList := CIDRList(cidrs)
|
||||
sort.Sort(&cidrList)
|
||||
|
||||
m.ip4 = make([]uint32, 0, ip4Count)
|
||||
m.prefix4 = make([]uint8, 0, ip4Count)
|
||||
m.ip6 = make([]ipv6, 0, ip6Count)
|
||||
m.prefix6 = make([]uint8, 0, ip6Count)
|
||||
|
||||
for _, cidr := range cidrs {
|
||||
ip := cidr.Ip
|
||||
prefix := uint8(cidr.Prefix)
|
||||
switch len(ip) {
|
||||
case 4:
|
||||
m.ip4 = append(m.ip4, normalize4(binary.BigEndian.Uint32(ip), prefix))
|
||||
m.prefix4 = append(m.prefix4, prefix)
|
||||
case 16:
|
||||
ip6 := ipv6{
|
||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||
}
|
||||
ip6 = normalize6(ip6, prefix)
|
||||
|
||||
m.ip6 = append(m.ip6, ip6)
|
||||
m.prefix6 = append(m.prefix6, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) SetReverseMatch(isReverseMatch bool) {
|
||||
m.reverseMatch = isReverseMatch
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) match4(ip uint32) bool {
|
||||
if len(m.ip4) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if ip < m.ip4[0] {
|
||||
return false
|
||||
}
|
||||
|
||||
size := uint32(len(m.ip4))
|
||||
l := uint32(0)
|
||||
r := size
|
||||
for l < r {
|
||||
x := ((l + r) >> 1)
|
||||
if ip < m.ip4[x] {
|
||||
r = x
|
||||
continue
|
||||
}
|
||||
|
||||
nip := normalize4(ip, m.prefix4[x])
|
||||
if nip == m.ip4[x] {
|
||||
return true
|
||||
}
|
||||
|
||||
l = x + 1
|
||||
}
|
||||
|
||||
return l > 0 && normalize4(ip, m.prefix4[l-1]) == m.ip4[l-1]
|
||||
}
|
||||
|
||||
func less6(a ipv6, b ipv6) bool {
|
||||
return a.a < b.a || (a.a == b.a && a.b < b.b)
|
||||
}
|
||||
|
||||
func (m *GeoIPMatcher) match6(ip ipv6) bool {
|
||||
if len(m.ip6) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if less6(ip, m.ip6[0]) {
|
||||
return false
|
||||
}
|
||||
|
||||
size := uint32(len(m.ip6))
|
||||
l := uint32(0)
|
||||
r := size
|
||||
for l < r {
|
||||
x := (l + r) / 2
|
||||
if less6(ip, m.ip6[x]) {
|
||||
r = x
|
||||
continue
|
||||
}
|
||||
|
||||
if normalize6(ip, m.prefix6[x]) == m.ip6[x] {
|
||||
return true
|
||||
}
|
||||
|
||||
l = x + 1
|
||||
}
|
||||
|
||||
return l > 0 && normalize6(ip, m.prefix6[l-1]) == m.ip6[l-1]
|
||||
}
|
||||
|
||||
// Match returns true if the given ip is included by the GeoIP.
|
||||
func (m *GeoIPMatcher) Match(ip net.IP) bool {
|
||||
switch len(ip) {
|
||||
case 4:
|
||||
if m.reverseMatch {
|
||||
return !m.match4(binary.BigEndian.Uint32(ip))
|
||||
}
|
||||
return m.match4(binary.BigEndian.Uint32(ip))
|
||||
case 16:
|
||||
if m.reverseMatch {
|
||||
return !m.match6(ipv6{
|
||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||
})
|
||||
}
|
||||
return m.match6(ipv6{
|
||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||
})
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// GeoIPMatcherContainer is a container for GeoIPMatchers. It keeps unique copies of GeoIPMatcher by country code.
|
||||
type GeoIPMatcherContainer struct {
|
||||
matchers []*GeoIPMatcher
|
||||
}
|
||||
|
||||
// Add adds a new GeoIP set into the container.
|
||||
// If the country code of GeoIP is not empty, GeoIPMatcherContainer will try to find an existing one, instead of adding a new one.
|
||||
func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) {
|
||||
if len(geoip.CountryCode) > 0 {
|
||||
for _, m := range c.matchers {
|
||||
if m.countryCode == geoip.CountryCode && m.reverseMatch == geoip.ReverseMatch {
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m := &GeoIPMatcher{
|
||||
countryCode: geoip.CountryCode,
|
||||
reverseMatch: geoip.ReverseMatch,
|
||||
}
|
||||
if err := m.Init(geoip.Cidr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(geoip.CountryCode) > 0 {
|
||||
c.matchers = append(c.matchers, m)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var globalGeoIPContainer GeoIPMatcherContainer
|
||||
|
||||
type MultiGeoIPMatcher struct {
|
||||
matchers []*GeoIPMatcher
|
||||
}
|
||||
|
||||
func NewGeoIPMatcher(geoip *GeoIP) (*GeoIPMatcher, error) {
|
||||
matcher, err := globalGeoIPContainer.Add(geoip)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return matcher, nil
|
||||
}
|
||||
|
||||
func (m *MultiGeoIPMatcher) ApplyIp(ip net.IP) bool {
|
||||
for _, matcher := range m.matchers {
|
||||
if matcher.Match(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func NewMultiGeoIPMatcher(geoips []*GeoIP) (*MultiGeoIPMatcher, error) {
|
||||
var matchers []*GeoIPMatcher
|
||||
for _, geoip := range geoips {
|
||||
matcher, err := globalGeoIPContainer.Add(geoip)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
matchers = append(matchers, matcher)
|
||||
}
|
||||
|
||||
matcher := &MultiGeoIPMatcher{
|
||||
matchers: matchers,
|
||||
}
|
||||
|
||||
return matcher, nil
|
||||
}
|
||||
|
@ -7,10 +7,11 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -9,7 +9,6 @@ import (
|
||||
"github.com/Dreamacro/clash/component/geodata"
|
||||
"github.com/Dreamacro/clash/component/geodata/router"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@ -26,14 +25,10 @@ func ReadFile(path string) ([]byte, error) {
|
||||
}
|
||||
|
||||
func ReadAsset(file string) ([]byte, error) {
|
||||
return ReadFile(C.Path.Resolve(file))
|
||||
return ReadFile(C.Path.GetAssetLocation(file))
|
||||
}
|
||||
|
||||
func loadIP(filename, country string) ([]*router.CIDR, error) {
|
||||
geoipBytes, err := ReadAsset(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
||||
}
|
||||
func loadIP(geoipBytes []byte, country string) ([]*router.CIDR, error) {
|
||||
var geoipList router.GeoIPList
|
||||
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
|
||||
return nil, err
|
||||
@ -45,14 +40,10 @@ func loadIP(filename, country string) ([]*router.CIDR, error) {
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("country not found in %s%s%s", filename, ": ", country)
|
||||
return nil, fmt.Errorf("country %s not found", country)
|
||||
}
|
||||
|
||||
func loadSite(filename, list string) ([]*router.Domain, error) {
|
||||
geositeBytes, err := ReadAsset(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
||||
}
|
||||
func loadSite(geositeBytes []byte, list string) ([]*router.Domain, error) {
|
||||
var geositeList router.GeoSiteList
|
||||
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
|
||||
return nil, err
|
||||
@ -64,17 +55,33 @@ func loadSite(filename, list string) ([]*router.Domain, error) {
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("list not found in %s%s%s", filename, ": ", list)
|
||||
return nil, fmt.Errorf("list %s not found", list)
|
||||
}
|
||||
|
||||
type standardLoader struct{}
|
||||
|
||||
func (d standardLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
|
||||
return loadSite(filename, list)
|
||||
func (d standardLoader) LoadSiteByPath(filename, list string) ([]*router.Domain, error) {
|
||||
geositeBytes, err := ReadAsset(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
||||
}
|
||||
return loadSite(geositeBytes, list)
|
||||
}
|
||||
|
||||
func (d standardLoader) LoadIP(filename, country string) ([]*router.CIDR, error) {
|
||||
return loadIP(filename, country)
|
||||
func (d standardLoader) LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error) {
|
||||
return loadSite(geositeBytes, list)
|
||||
}
|
||||
|
||||
func (d standardLoader) LoadIPByPath(filename, country string) ([]*router.CIDR, error) {
|
||||
geoipBytes, err := ReadAsset(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
||||
}
|
||||
return loadIP(geoipBytes, country)
|
||||
}
|
||||
|
||||
func (d standardLoader) LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error) {
|
||||
return loadIP(geoipBytes, country)
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
@ -1,11 +1,51 @@
|
||||
package geodata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Dreamacro/clash/component/geodata/router"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
var geoLoaderName = "memconservative"
|
||||
|
||||
// geoLoaderName = "standard"
|
||||
|
||||
func LoaderName() string {
|
||||
return geoLoaderName
|
||||
}
|
||||
|
||||
func SetLoader(newLoader string) {
|
||||
if newLoader == "memc" {
|
||||
newLoader = "memconservative"
|
||||
}
|
||||
geoLoaderName = newLoader
|
||||
}
|
||||
|
||||
func Verify(name string) error {
|
||||
switch name {
|
||||
case C.GeositeName:
|
||||
_, _, err := LoadGeoSiteMatcher("CN")
|
||||
return err
|
||||
case C.GeoipName:
|
||||
_, _, err := LoadGeoIPMatcher("CN")
|
||||
return err
|
||||
default:
|
||||
return fmt.Errorf("not support name")
|
||||
}
|
||||
}
|
||||
|
||||
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
||||
geoLoaderName := "standard"
|
||||
if len(countryCode) == 0 {
|
||||
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||
}
|
||||
|
||||
not := false
|
||||
if countryCode[0] == '!' {
|
||||
not = true
|
||||
countryCode = countryCode[1:]
|
||||
}
|
||||
|
||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
@ -21,10 +61,44 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
||||
matcher, err := router.NewDomainMatcher(domains)
|
||||
mph:minimal perfect hash algorithm
|
||||
*/
|
||||
matcher, err := router.NewMphMatcherGroup(domains)
|
||||
matcher, err := router.NewMphMatcherGroup(domains, not)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return matcher, len(domains), nil
|
||||
}
|
||||
|
||||
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
||||
if len(country) == 0 {
|
||||
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||
}
|
||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
not := false
|
||||
if country[0] == '!' {
|
||||
not = true
|
||||
country = country[1:]
|
||||
}
|
||||
|
||||
records, err := geoLoader.LoadGeoIP(country)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
geoIP := &router.GeoIP{
|
||||
CountryCode: country,
|
||||
Cidr: records,
|
||||
ReverseMatch: not,
|
||||
}
|
||||
|
||||
matcher, err := router.NewGeoIPMatcher(geoIP)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return matcher, len(records), nil
|
||||
}
|
||||
|
64
component/http/http.go
Normal file
64
component/http/http.go
Normal file
@ -0,0 +1,64 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
URL "net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/listener/inner"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
const (
|
||||
UA = "Clash"
|
||||
)
|
||||
|
||||
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
||||
method = strings.ToUpper(method)
|
||||
urlRes, err := URL.Parse(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, urlRes.String(), body)
|
||||
for k, v := range header {
|
||||
for _, v := range v {
|
||||
req.Header.Add(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := header["User-Agent"]; !ok {
|
||||
req.Header.Set("User-Agent", UA)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if user := urlRes.User; user != nil {
|
||||
password, _ := user.Password()
|
||||
req.SetBasicAuth(user.Username(), password)
|
||||
}
|
||||
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
transport := &http.Transport{
|
||||
// from http.DefaultTransport
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
log.Infoln(urlRes.String())
|
||||
conn := inner.HandleTcp(address, urlRes.Hostname())
|
||||
return conn, nil
|
||||
},
|
||||
}
|
||||
|
||||
client := http.Client{Transport: transport}
|
||||
return client.Do(req)
|
||||
}
|
@ -5,7 +5,6 @@ import (
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
)
|
||||
|
||||
|
@ -13,6 +13,8 @@ var (
|
||||
ErrInvalidNetwork = errors.New("invalid network")
|
||||
ErrPlatformNotSupport = errors.New("not support on this platform")
|
||||
ErrNotFound = errors.New("process not found")
|
||||
|
||||
enableFindProcess = true
|
||||
)
|
||||
|
||||
const (
|
||||
@ -20,12 +22,26 @@ const (
|
||||
UDP = "udp"
|
||||
)
|
||||
|
||||
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (string, error) {
|
||||
func EnableFindProcess(e bool) {
|
||||
enableFindProcess = e
|
||||
}
|
||||
|
||||
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (int32, string, error) {
|
||||
return findProcessName(network, srcIP, srcPort)
|
||||
}
|
||||
|
||||
func FindUid(network string, srcIP netip.Addr, srcPort int) (int32, error) {
|
||||
_, uid, err := resolveSocketByNetlink(network, srcIP, srcPort)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
return uid, nil
|
||||
}
|
||||
|
||||
func ShouldFindProcess(metadata *C.Metadata) bool {
|
||||
if metadata.Process != "" {
|
||||
if !enableFindProcess ||
|
||||
metadata.Process != "" ||
|
||||
metadata.ProcessPath != "" {
|
||||
return false
|
||||
}
|
||||
for _, ip := range localIPs {
|
||||
|
@ -7,7 +7,6 @@ import (
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/clash/common/nnip"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
@ -17,7 +16,11 @@ const (
|
||||
proccallnumpidinfo = 0x2
|
||||
)
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||
return 0, 0, ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, port int) (int32, string, error) {
|
||||
var spath string
|
||||
switch network {
|
||||
case TCP:
|
||||
@ -25,14 +28,14 @@ func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
||||
case UDP:
|
||||
spath = "net.inet.udp.pcblist_n"
|
||||
default:
|
||||
return "", ErrInvalidNetwork
|
||||
return -1, "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
isIPv4 := ip.Is4()
|
||||
|
||||
value, err := syscall.Sysctl(spath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return -1, "", err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
@ -77,10 +80,11 @@ func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
||||
|
||||
// xsocket_n.so_last_pid
|
||||
pid := readNativeUint32(buf[so+68 : so+72])
|
||||
return getExecPathFromPID(pid)
|
||||
pp, err := getExecPathFromPID(pid)
|
||||
return -1, pp, err
|
||||
}
|
||||
|
||||
return "", ErrNotFound
|
||||
return -1, "", ErrNotFound
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
|
@ -21,7 +21,11 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||
return 0, 0, ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||
once.Do(func() {
|
||||
if err := initSearcher(); err != nil {
|
||||
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||
@ -31,7 +35,7 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
||||
})
|
||||
|
||||
if defaultSearcher == nil {
|
||||
return "", ErrPlatformNotSupport
|
||||
return -1, "", ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
var spath string
|
||||
@ -42,21 +46,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
||||
case UDP:
|
||||
spath = "net.inet.udp.pcblist"
|
||||
default:
|
||||
return "", ErrInvalidNetwork
|
||||
return -1, "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
value, err := syscall.Sysctl(spath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return -1, "", err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return -1, "", err
|
||||
}
|
||||
|
||||
return getExecPathFromPID(pid)
|
||||
pp, err := getExecPathFromPID(pid)
|
||||
return -1, pp, err
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
|
@ -8,6 +8,8 @@ import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unicode"
|
||||
@ -32,13 +34,13 @@ const (
|
||||
pathProc = "/proc"
|
||||
)
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return -1, "", err
|
||||
}
|
||||
|
||||
return resolveProcessNameByProcSearch(inode, uid)
|
||||
pp, err := resolveProcessNameByProcSearch(inode, uid)
|
||||
return uid, pp, err
|
||||
}
|
||||
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||
@ -108,7 +110,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32,
|
||||
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
||||
}
|
||||
|
||||
inode, uid := unpackSocketDiagResponse(&messages[0])
|
||||
inode, uid := unpackSocketDiagResponse(&message)
|
||||
if inode < 0 || uid < 0 {
|
||||
return 0, 0, fmt.Errorf("invalid inode(%d) or uid(%d)", inode, uid)
|
||||
}
|
||||
@ -196,8 +198,19 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
if bytes.Equal(buffer[:n], socket) {
|
||||
return os.Readlink(path.Join(processPath, "exe"))
|
||||
if runtime.GOOS == "android" {
|
||||
if bytes.Equal(buffer[:n], socket) {
|
||||
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return splitCmdline(cmdline), nil
|
||||
}
|
||||
} else {
|
||||
if bytes.Equal(buffer[:n], socket) {
|
||||
return os.Readlink(path.Join(processPath, "exe"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -205,6 +218,19 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
||||
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
||||
}
|
||||
|
||||
func splitCmdline(cmdline []byte) string {
|
||||
cmdline = bytes.Trim(cmdline, " ")
|
||||
|
||||
idx := bytes.IndexFunc(cmdline, func(r rune) bool {
|
||||
return unicode.IsControl(r) || unicode.IsSpace(r)
|
||||
})
|
||||
|
||||
if idx == -1 {
|
||||
return filepath.Base(string(cmdline))
|
||||
}
|
||||
return filepath.Base(string(cmdline[:idx]))
|
||||
}
|
||||
|
||||
func isPid(s string) bool {
|
||||
return strings.IndexFunc(s, func(r rune) bool {
|
||||
return !unicode.IsDigit(r)
|
||||
|
@ -4,6 +4,10 @@ package process
|
||||
|
||||
import "net/netip"
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
||||
return "", ErrPlatformNotSupport
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||
return -1, "", ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||
return 0, 0, ErrPlatformNotSupport
|
||||
}
|
||||
|
@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/common/nnip"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
@ -29,6 +28,10 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||
return 0, 0, ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
func initWin32API() error {
|
||||
h, err := windows.LoadLibrary("iphlpapi.dll")
|
||||
if err != nil {
|
||||
@ -58,7 +61,7 @@ func initWin32API() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) {
|
||||
once.Do(func() {
|
||||
err := initWin32API()
|
||||
if err != nil {
|
||||
@ -82,21 +85,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
||||
fn = getExUDPTable
|
||||
class = udpTablePid
|
||||
default:
|
||||
return "", ErrInvalidNetwork
|
||||
return -1, "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
buf, err := getTransportTable(fn, family, class)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return -1, "", err
|
||||
}
|
||||
|
||||
s := newSearcher(family == windows.AF_INET, network == TCP)
|
||||
|
||||
pid, err := s.Search(buf, ip, uint16(srcPort))
|
||||
if err != nil {
|
||||
return "", err
|
||||
return -1, "", err
|
||||
}
|
||||
return getExecPathFromPID(pid)
|
||||
pp, err := getExecPathFromPID(pid)
|
||||
return -1, pp, err
|
||||
}
|
||||
|
||||
type searcher struct {
|
||||
@ -215,8 +219,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
||||
uintptr(h),
|
||||
uintptr(1),
|
||||
uintptr(unsafe.Pointer(&buf[0])),
|
||||
uintptr(unsafe.Pointer(&size)),
|
||||
)
|
||||
uintptr(unsafe.Pointer(&size)))
|
||||
if r1 == 0 {
|
||||
return "", err
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ import (
|
||||
"github.com/Dreamacro/clash/component/profile"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
|
@ -40,6 +40,10 @@ type Resolver interface {
|
||||
ResolveIP(host string) (ip netip.Addr, err error)
|
||||
ResolveIPv4(host string) (ip netip.Addr, err error)
|
||||
ResolveIPv6(host string) (ip netip.Addr, err error)
|
||||
ResolveAllIP(host string) (ip []netip.Addr, err error)
|
||||
ResolveAllIPPrimaryIPv4(host string) (ips []netip.Addr, err error)
|
||||
ResolveAllIPv4(host string) (ips []netip.Addr, err error)
|
||||
ResolveAllIPv6(host string) (ips []netip.Addr, err error)
|
||||
}
|
||||
|
||||
// ResolveIPv4 with a host, return ipv4
|
||||
@ -48,43 +52,11 @@ func ResolveIPv4(host string) (netip.Addr, error) {
|
||||
}
|
||||
|
||||
func ResolveIPv4WithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
if ip := node.Data; ip.Is4() {
|
||||
return ip, nil
|
||||
}
|
||||
if ips, err := ResolveAllIPv4WithResolver(host, r); err == nil {
|
||||
return ips[rand.Intn(len(ips))], nil
|
||||
} else {
|
||||
return netip.Addr{}, nil
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
if ip.Is4() {
|
||||
return ip, nil
|
||||
}
|
||||
return netip.Addr{}, ErrIPVersion
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
return r.ResolveIPv4(host)
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||
defer cancel()
|
||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
||||
if err != nil {
|
||||
return netip.Addr{}, err
|
||||
} else if len(ipAddrs) == 0 {
|
||||
return netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
ip := ipAddrs[rand.Intn(len(ipAddrs))].To4()
|
||||
if ip == nil {
|
||||
return netip.Addr{}, ErrIPVersion
|
||||
}
|
||||
|
||||
return netip.AddrFrom4(*(*[4]byte)(ip)), nil
|
||||
}
|
||||
|
||||
return netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
// ResolveIPv6 with a host, return ipv6
|
||||
@ -93,74 +65,20 @@ func ResolveIPv6(host string) (netip.Addr, error) {
|
||||
}
|
||||
|
||||
func ResolveIPv6WithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||
if DisableIPv6 {
|
||||
return netip.Addr{}, ErrIPv6Disabled
|
||||
if ips, err := ResolveAllIPv6WithResolver(host, r); err == nil {
|
||||
return ips[rand.Intn(len(ips))], nil
|
||||
} else {
|
||||
return netip.Addr{}, err
|
||||
}
|
||||
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
if ip := node.Data; ip.Is6() {
|
||||
return ip, nil
|
||||
}
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
if ip.Is6() {
|
||||
return ip, nil
|
||||
}
|
||||
return netip.Addr{}, ErrIPVersion
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
return r.ResolveIPv6(host)
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||
defer cancel()
|
||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip6", host)
|
||||
if err != nil {
|
||||
return netip.Addr{}, err
|
||||
} else if len(ipAddrs) == 0 {
|
||||
return netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
return netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))])), nil
|
||||
}
|
||||
|
||||
return netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
||||
func ResolveIPWithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
return node.Data, nil
|
||||
if ips, err := ResolveAllIPPrimaryIPv4WithResolver(host, r); err == nil {
|
||||
return ips[rand.Intn(len(ips))], nil
|
||||
} else {
|
||||
return netip.Addr{}, err
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
if DisableIPv6 {
|
||||
return r.ResolveIPv4(host)
|
||||
}
|
||||
return r.ResolveIP(host)
|
||||
} else if DisableIPv6 {
|
||||
return ResolveIPv4(host)
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return netip.Addr{}, err
|
||||
}
|
||||
|
||||
return nnip.IpToAddr(ipAddr.IP), nil
|
||||
}
|
||||
|
||||
return netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
// ResolveIP with a host, return ip
|
||||
@ -171,23 +89,217 @@ func ResolveIP(host string) (netip.Addr, error) {
|
||||
// ResolveIPv4ProxyServerHost proxies server host only
|
||||
func ResolveIPv4ProxyServerHost(host string) (netip.Addr, error) {
|
||||
if ProxyServerHostResolver != nil {
|
||||
return ResolveIPv4WithResolver(host, ProxyServerHostResolver)
|
||||
if ip, err := ResolveIPv4WithResolver(host, ProxyServerHostResolver); err != nil {
|
||||
return ResolveIPv4(host)
|
||||
} else {
|
||||
return ip, nil
|
||||
}
|
||||
}
|
||||
|
||||
return ResolveIPv4(host)
|
||||
}
|
||||
|
||||
// ResolveIPv6ProxyServerHost proxies server host only
|
||||
func ResolveIPv6ProxyServerHost(host string) (netip.Addr, error) {
|
||||
if ProxyServerHostResolver != nil {
|
||||
return ResolveIPv6WithResolver(host, ProxyServerHostResolver)
|
||||
if ip, err := ResolveIPv6WithResolver(host, ProxyServerHostResolver); err != nil {
|
||||
return ResolveIPv6(host)
|
||||
} else {
|
||||
return ip, nil
|
||||
}
|
||||
}
|
||||
|
||||
return ResolveIPv6(host)
|
||||
}
|
||||
|
||||
// ResolveProxyServerHost proxies server host only
|
||||
func ResolveProxyServerHost(host string) (netip.Addr, error) {
|
||||
if ProxyServerHostResolver != nil {
|
||||
return ResolveIPWithResolver(host, ProxyServerHostResolver)
|
||||
if ip, err := ResolveIPWithResolver(host, ProxyServerHostResolver); err != nil {
|
||||
return ResolveIP(host)
|
||||
} else {
|
||||
return ip, err
|
||||
}
|
||||
}
|
||||
|
||||
return ResolveIP(host)
|
||||
}
|
||||
|
||||
func ResolveAllIPv6WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||
if DisableIPv6 {
|
||||
return []netip.Addr{}, ErrIPv6Disabled
|
||||
}
|
||||
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
if ip := node.Data; ip.Is6() {
|
||||
return []netip.Addr{ip}, nil
|
||||
}
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
if ip.Is6() {
|
||||
return []netip.Addr{ip}, nil
|
||||
}
|
||||
return []netip.Addr{}, ErrIPVersion
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
return r.ResolveAllIPv6(host)
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||
defer cancel()
|
||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip6", host)
|
||||
if err != nil {
|
||||
return []netip.Addr{}, err
|
||||
} else if len(ipAddrs) == 0 {
|
||||
return []netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
return []netip.Addr{netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))]))}, nil
|
||||
}
|
||||
|
||||
return []netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
if ip := node.Data; ip.Is4() {
|
||||
return []netip.Addr{node.Data}, nil
|
||||
}
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
if ip.Is4() {
|
||||
return []netip.Addr{ip}, nil
|
||||
}
|
||||
return []netip.Addr{}, ErrIPVersion
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
return r.ResolveAllIPv4(host)
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||
defer cancel()
|
||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
||||
if err != nil {
|
||||
return []netip.Addr{}, err
|
||||
} else if len(ipAddrs) == 0 {
|
||||
return []netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
ip := ipAddrs[rand.Intn(len(ipAddrs))].To4()
|
||||
if ip == nil {
|
||||
return []netip.Addr{}, ErrIPVersion
|
||||
}
|
||||
|
||||
return []netip.Addr{netip.AddrFrom4(*(*[4]byte)(ip))}, nil
|
||||
}
|
||||
|
||||
return []netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
return []netip.Addr{node.Data}, nil
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
if DisableIPv6 {
|
||||
return r.ResolveAllIPv4(host)
|
||||
}
|
||||
|
||||
return r.ResolveAllIP(host)
|
||||
} else if DisableIPv6 {
|
||||
return ResolveAllIPv4(host)
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
return []netip.Addr{ip}, nil
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return []netip.Addr{}, err
|
||||
}
|
||||
|
||||
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
||||
}
|
||||
|
||||
return []netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
func ResolveAllIPPrimaryIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||
if node := DefaultHosts.Search(host); node != nil {
|
||||
return []netip.Addr{node.Data}, nil
|
||||
}
|
||||
|
||||
if r != nil {
|
||||
if DisableIPv6 {
|
||||
return r.ResolveAllIPv4(host)
|
||||
}
|
||||
|
||||
return r.ResolveAllIPPrimaryIPv4(host)
|
||||
} else if DisableIPv6 {
|
||||
return ResolveAllIPv4(host)
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err == nil {
|
||||
return []netip.Addr{ip}, nil
|
||||
}
|
||||
|
||||
if DefaultResolver == nil {
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return []netip.Addr{}, err
|
||||
}
|
||||
|
||||
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
||||
}
|
||||
|
||||
return []netip.Addr{}, ErrIPNotFound
|
||||
}
|
||||
|
||||
func ResolveAllIP(host string) ([]netip.Addr, error) {
|
||||
return ResolveAllIPWithResolver(host, DefaultResolver)
|
||||
}
|
||||
|
||||
func ResolveAllIPv4(host string) ([]netip.Addr, error) {
|
||||
return ResolveAllIPv4WithResolver(host, DefaultResolver)
|
||||
}
|
||||
|
||||
func ResolveAllIPv6(host string) ([]netip.Addr, error) {
|
||||
return ResolveAllIPv6WithResolver(host, DefaultResolver)
|
||||
}
|
||||
|
||||
func ResolveAllIPv6ProxyServerHost(host string) ([]netip.Addr, error) {
|
||||
if ProxyServerHostResolver != nil {
|
||||
return ResolveAllIPv6WithResolver(host, ProxyServerHostResolver)
|
||||
}
|
||||
|
||||
return ResolveAllIPv6(host)
|
||||
}
|
||||
|
||||
func ResolveAllIPv4ProxyServerHost(host string) ([]netip.Addr, error) {
|
||||
if ProxyServerHostResolver != nil {
|
||||
return ResolveAllIPv4WithResolver(host, ProxyServerHostResolver)
|
||||
}
|
||||
|
||||
return ResolveAllIPv4(host)
|
||||
}
|
||||
|
||||
func ResolveAllIPProxyServerHost(host string) ([]netip.Addr, error) {
|
||||
if ProxyServerHostResolver != nil {
|
||||
return ResolveAllIPWithResolver(host, ProxyServerHostResolver)
|
||||
}
|
||||
|
||||
return ResolveAllIP(host)
|
||||
}
|
||||
|
@ -1,10 +0,0 @@
|
||||
//go:build build_actions
|
||||
|
||||
package script
|
||||
|
||||
/*
|
||||
#cgo windows,amd64 CFLAGS: -ID:/python-amd64/include -DMS_WIN64
|
||||
|
||||
#cgo windows,amd64 LDFLAGS: -LD:/python-amd64/libs -lpython39 -lpthread -lm
|
||||
*/
|
||||
import "C"
|
@ -1,8 +0,0 @@
|
||||
//go:build build_local
|
||||
|
||||
package script
|
||||
|
||||
/*
|
||||
#cgo pkg-config: python3-embed
|
||||
*/
|
||||
import "C"
|
@ -1,24 +0,0 @@
|
||||
//go:build !build_local
|
||||
|
||||
package script
|
||||
|
||||
/*
|
||||
#cgo linux,amd64 pkg-config: python3-embed
|
||||
|
||||
#cgo darwin,amd64 CFLAGS: -I/build/python/python-3.9.7-darwin-amd64/include/python3.9
|
||||
#cgo darwin,arm64 CFLAGS: -I/build/python/python-3.9.7-darwin-arm64/include/python3.9
|
||||
#cgo windows,amd64 CFLAGS: -I/build/python/python-3.9.7-windows-amd64/include -DMS_WIN64
|
||||
#cgo windows,386 CFLAGS: -I/build/python/python-3.9.7-windows-386/include
|
||||
//#cgo linux,amd64 CFLAGS: -I/home/runner/work/clash/clash/bin/python/python-3.9.7-linux-amd64/include/python3.9
|
||||
//#cgo linux,arm64 CFLAGS: -I/build/python/python-3.9.7-linux-arm64/include/python3.9
|
||||
//#cgo linux,386 CFLAGS: -I/build/python/python-3.9.7-linux-386/include/python3.9
|
||||
|
||||
#cgo darwin,amd64 LDFLAGS: -L/build/python/python-3.9.7-darwin-amd64/lib -lpython3.9 -ldl -framework CoreFoundation
|
||||
#cgo darwin,arm64 LDFLAGS: -L/build/python/python-3.9.7-darwin-arm64/lib -lpython3.9 -ldl -framework CoreFoundation
|
||||
#cgo windows,amd64 LDFLAGS: -L/build/python/python-3.9.7-windows-amd64/lib -lpython39 -lpthread -lm
|
||||
#cgo windows,386 LDFLAGS: -L/build/python/python-3.9.7-windows-386/lib -lpython39 -lpthread -lm
|
||||
//#cgo linux,amd64 LDFLAGS: -L/home/runner/work/clash/clash/bin/python/python-3.9.7-linux-amd64/lib -lpython3.9 -lpthread -ldl -lutil -lm
|
||||
//#cgo linux,arm64 LDFLAGS: -L/build/python/python-3.9.7-linux-arm64/lib -lpython3.9 -lpthread -ldl -lutil -lm
|
||||
//#cgo linux,386 LDFLAGS: -L/build/python/python-3.9.7-linux-386/lib -lpython3.9 -lpthread -ldl -lutil -lm
|
||||
*/
|
||||
import "C"
|
@ -1,742 +0,0 @@
|
||||
#define PY_SSIZE_T_CLEAN
|
||||
|
||||
#include "clash_module.h"
|
||||
#include <structmember.h>
|
||||
|
||||
PyObject *clash_module;
|
||||
PyObject *main_fn;
|
||||
PyObject *clash_context;
|
||||
|
||||
// init_python
|
||||
void init_python(const char *program, const char *path) {
|
||||
|
||||
// Py_NoSiteFlag = 1;
|
||||
// Py_FrozenFlag = 1;
|
||||
// Py_IgnoreEnvironmentFlag = 1;
|
||||
// Py_IsolatedFlag = 1;
|
||||
|
||||
append_inittab();
|
||||
|
||||
wchar_t *programName = Py_DecodeLocale(program, NULL);
|
||||
if (programName != NULL) {
|
||||
Py_SetProgramName(programName);
|
||||
PyMem_RawFree(programName);
|
||||
}
|
||||
|
||||
// wchar_t *newPath = Py_DecodeLocale(path, NULL);
|
||||
// if (newPath != NULL) {
|
||||
// Py_SetPath(newPath);
|
||||
// PyMem_RawFree(newPath);
|
||||
// }
|
||||
|
||||
// Py_Initialize();
|
||||
Py_InitializeEx(0);
|
||||
|
||||
char *pathPrefix = "import sys; sys.path.append('";
|
||||
char *pathSuffix = "')";
|
||||
char *newPath = (char *) malloc(strlen(pathPrefix) + strlen(path) + strlen(pathSuffix));
|
||||
sprintf(newPath, "%s%s%s", pathPrefix, path, pathSuffix);
|
||||
|
||||
PyRun_SimpleString(newPath);
|
||||
free(newPath);
|
||||
|
||||
/* Optionally import the module; alternatively,
|
||||
import can be deferred until the embedded script
|
||||
imports it. */
|
||||
clash_module = PyImport_ImportModule("clash");
|
||||
}
|
||||
|
||||
// Load function, same as "import module_name.func_name as obj" in Python
|
||||
// Returns the function object or NULL if not found
|
||||
PyObject *load_func(const char *module_name, char *func_name) {
|
||||
// Import the module
|
||||
PyObject *py_mod_name = PyUnicode_FromString(module_name);
|
||||
if (py_mod_name == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
PyObject *module = PyImport_Import(py_mod_name);
|
||||
Py_DECREF(py_mod_name);
|
||||
if (module == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Get function, same as "getattr(module, func_name)" in Python
|
||||
PyObject *func = PyObject_GetAttrString(module, func_name);
|
||||
Py_DECREF(module);
|
||||
return func;
|
||||
}
|
||||
|
||||
// Return last error as char *, NULL if there was no error
|
||||
const char *py_last_error() {
|
||||
PyObject *err = PyErr_Occurred();
|
||||
if (err == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
PyObject *type, *value, *traceback;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
|
||||
if (value == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
PyObject *str = PyObject_Str(value);
|
||||
const char *utf8 = PyUnicode_AsUTF8(str);
|
||||
Py_DECREF(str);
|
||||
PyErr_Clear();
|
||||
return utf8;
|
||||
}
|
||||
|
||||
void py_clear(PyObject *obj) {
|
||||
Py_CLEAR(obj);
|
||||
}
|
||||
|
||||
void load_main_func() {
|
||||
main_fn = load_func(CLASH_SCRIPT_MODULE_NAME, "main");
|
||||
}
|
||||
|
||||
/** callback function, that call go function by python3 script. **/
|
||||
|
||||
resolve_ip_callback resolve_ip_callback_fn;
|
||||
|
||||
geoip_callback geoip_callback_fn;
|
||||
|
||||
rule_provider_callback rule_provider_callback_fn;
|
||||
|
||||
log_callback log_callback_fn;
|
||||
|
||||
void
|
||||
set_resolve_ip_callback(resolve_ip_callback cb)
|
||||
{
|
||||
resolve_ip_callback_fn = cb;
|
||||
}
|
||||
|
||||
void
|
||||
set_geoip_callback(geoip_callback cb)
|
||||
{
|
||||
geoip_callback_fn = cb;
|
||||
}
|
||||
|
||||
void
|
||||
set_rule_provider_callback(rule_provider_callback cb)
|
||||
{
|
||||
rule_provider_callback_fn = cb;
|
||||
}
|
||||
|
||||
void
|
||||
set_log_callback(log_callback cb)
|
||||
{
|
||||
log_callback_fn = cb;
|
||||
}
|
||||
|
||||
/** end callback function **/
|
||||
|
||||
/* --------------------------------------------------------------------- */
|
||||
|
||||
/* RuleProvider objects */
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
PyObject *name; /* rule provider name */
|
||||
} RuleProviderObject;
|
||||
|
||||
static int
|
||||
RuleProvider_traverse(RuleProviderObject *self, visitproc visit, void *arg)
|
||||
{
|
||||
Py_VISIT(self->name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
RuleProvider_clear(RuleProviderObject *self)
|
||||
{
|
||||
Py_CLEAR(self->name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
RuleProvider_dealloc(RuleProviderObject *self)
|
||||
{
|
||||
PyObject_GC_UnTrack(self);
|
||||
RuleProvider_clear(self);
|
||||
Py_TYPE(self)->tp_free((PyObject *) self);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
RuleProvider_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
RuleProviderObject *self;
|
||||
self = (RuleProviderObject *) type->tp_alloc(type, 0);
|
||||
if (self != NULL) {
|
||||
self->name = PyUnicode_FromString("");
|
||||
if (self->name == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
return (PyObject *) self;
|
||||
}
|
||||
|
||||
static int
|
||||
RuleProvider_init(RuleProviderObject *self, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
static char *kwlist[] = {"name", NULL};
|
||||
PyObject *name = NULL, *tmp;
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Us", kwlist, &name))
|
||||
return -1;
|
||||
|
||||
if (name) {
|
||||
tmp = self->name;
|
||||
Py_INCREF(name);
|
||||
self->name = name;
|
||||
Py_DECREF(tmp);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//static PyMemberDef RuleProvider_members[] = {
|
||||
// {"adapter_type", T_STRING, offsetof(RuleProviderObject, adapter_type), 0,
|
||||
// "adapter type"},
|
||||
// {NULL} /* Sentinel */
|
||||
//};
|
||||
|
||||
static PyObject *
|
||||
RuleProvider_getname(RuleProviderObject *self, void *closure)
|
||||
{
|
||||
Py_INCREF(self->name);
|
||||
return self->name;
|
||||
}
|
||||
|
||||
static int
|
||||
RuleProvider_setname(RuleProviderObject *self, PyObject *value, void *closure)
|
||||
{
|
||||
if (value == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError, "Cannot delete the name attribute");
|
||||
return -1;
|
||||
}
|
||||
if (!PyUnicode_Check(value)) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"The name attribute value must be a string");
|
||||
return -1;
|
||||
}
|
||||
Py_INCREF(value);
|
||||
Py_CLEAR(self->name);
|
||||
self->name = value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyGetSetDef RuleProvider_getsetters[] = {
|
||||
{"name", (getter) RuleProvider_getname, (setter) RuleProvider_setname,
|
||||
"name", NULL},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
RuleProvider_name(RuleProviderObject *self, PyObject *Py_UNUSED(ignored))
|
||||
{
|
||||
Py_INCREF(self->name);
|
||||
return self->name;
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
RuleProvider_match(RuleProviderObject *self, PyObject *args)
|
||||
{
|
||||
PyObject *result;
|
||||
PyObject *tmp;
|
||||
const char *provider_name;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &tmp)) //Format "O","O!","O&": Borrowed reference.
|
||||
return NULL;
|
||||
|
||||
if (tmp == NULL)
|
||||
Py_RETURN_FALSE;
|
||||
|
||||
Py_INCREF(tmp);
|
||||
// PyObject *py_src_port = PyDict_GetItemString(tmp, "src_port"); //Return value: Borrowed reference.
|
||||
// PyObject *py_dst_port = PyDict_GetItemString(tmp, "dst_port"); //Return value: Borrowed reference.
|
||||
// Py_INCREF(py_src_port);
|
||||
// Py_INCREF(py_dst_port);
|
||||
// char *c_src_port = (char *) malloc(PyLong_AsSize_t(py_src_port));
|
||||
// char *c_dst_port = (char *) malloc(PyLong_AsSize_t(py_dst_port));
|
||||
// sprintf(c_src_port, "%ld", PyLong_AsLong(py_src_port));
|
||||
// sprintf(c_dst_port, "%ld", PyLong_AsLong(py_dst_port));
|
||||
|
||||
struct Metadata metadata = {
|
||||
.type = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "type")), // PyDict_GetItemString() Return value: Borrowed reference.
|
||||
.network = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "network")),
|
||||
.process_name = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "process_name")),
|
||||
.process_path = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "process_path")),
|
||||
.host = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "host")),
|
||||
.src_ip = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "src_ip")),
|
||||
.src_port = (unsigned short)PyLong_AsUnsignedLong(PyDict_GetItemString(tmp, "src_port")),
|
||||
.dst_ip = PyUnicode_AsUTF8(PyDict_GetItemString(tmp, "dst_ip")),
|
||||
.dst_port = (unsigned short)PyLong_AsUnsignedLong(PyDict_GetItemString(tmp, "dst_port"))
|
||||
};
|
||||
|
||||
// Py_DECREF(py_src_port);
|
||||
// Py_DECREF(py_dst_port);
|
||||
|
||||
Py_INCREF(self->name);
|
||||
provider_name = PyUnicode_AsUTF8(self->name);
|
||||
Py_DECREF(self->name);
|
||||
Py_DECREF(tmp);
|
||||
|
||||
int rs = rule_provider_callback_fn(provider_name, &metadata);
|
||||
|
||||
result = (rs == 1) ? Py_True : Py_False;
|
||||
Py_INCREF(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
static PyMethodDef RuleProvider_methods[] = {
|
||||
{"name", (PyCFunction) RuleProvider_name, METH_NOARGS,
|
||||
"Return the RuleProvider name"
|
||||
},
|
||||
{"match", (PyCFunction) RuleProvider_match, METH_VARARGS,
|
||||
"Match the rule by the RuleProvider, match(metadata) -> boolean"
|
||||
},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyTypeObject RuleProviderType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "clash.RuleProvider",
|
||||
.tp_doc = "Clash RuleProvider objects",
|
||||
.tp_basicsize = sizeof(RuleProviderObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
|
||||
.tp_new = RuleProvider_new,
|
||||
.tp_init = (initproc) RuleProvider_init,
|
||||
.tp_dealloc = (destructor) RuleProvider_dealloc,
|
||||
.tp_traverse = (traverseproc) RuleProvider_traverse,
|
||||
.tp_clear = (inquiry) RuleProvider_clear,
|
||||
// .tp_members = RuleProvider_members,
|
||||
.tp_methods = RuleProvider_methods,
|
||||
.tp_getset = RuleProvider_getsetters,
|
||||
};
|
||||
|
||||
/* end RuleProvider objects */
|
||||
/* --------------------------------------------------------------------- */
|
||||
|
||||
/* Context objects */
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
PyObject *rule_providers; /* Dict<String, RuleProvider> */
|
||||
} ContextObject;
|
||||
|
||||
static int
|
||||
Context_traverse(ContextObject *self, visitproc visit, void *arg)
|
||||
{
|
||||
Py_VISIT(self->rule_providers);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
Context_clear(ContextObject *self)
|
||||
{
|
||||
Py_CLEAR(self->rule_providers);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
Context_dealloc(ContextObject *self)
|
||||
{
|
||||
PyObject_GC_UnTrack(self);
|
||||
Context_clear(self);
|
||||
Py_TYPE(self)->tp_free((PyObject *) self);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
ContextObject *self;
|
||||
self = (ContextObject *) type->tp_alloc(type, 0);
|
||||
if (self != NULL) {
|
||||
self->rule_providers = PyDict_New();
|
||||
if (self->rule_providers == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
return (PyObject *) self;
|
||||
}
|
||||
|
||||
static int
|
||||
Context_init(ContextObject *self, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
static char *kwlist[] = {"rule_providers", NULL};
|
||||
PyObject *rule_providers = NULL, *tmp;
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
|
||||
&rule_providers))
|
||||
return -1;
|
||||
|
||||
if (rule_providers) {
|
||||
tmp = self->rule_providers;
|
||||
Py_INCREF(rule_providers);
|
||||
self->rule_providers = rule_providers;
|
||||
Py_DECREF(tmp);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Context_getrule_providers(ContextObject *self, void *closure)
|
||||
{
|
||||
Py_INCREF(self->rule_providers);
|
||||
return self->rule_providers;
|
||||
}
|
||||
|
||||
static int
|
||||
Context_setrule_providers(ContextObject *self, PyObject *value, void *closure)
|
||||
{
|
||||
if (value == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError, "Cannot delete the rule_providers attribute");
|
||||
return -1;
|
||||
}
|
||||
if (!PyDict_Check(value)) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"The rule_providers attribute value must be a dict");
|
||||
return -1;
|
||||
}
|
||||
Py_INCREF(value);
|
||||
Py_CLEAR(self->rule_providers);
|
||||
self->rule_providers = value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyGetSetDef Context_getsetters[] = {
|
||||
{"rule_providers", (getter) Context_getrule_providers, (setter) Context_setrule_providers,
|
||||
"rule_providers", NULL},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
Context_resolve_ip(PyObject *self, PyObject *args)
|
||||
{
|
||||
const char *host;
|
||||
const char *ip;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s", &host))
|
||||
return NULL;
|
||||
|
||||
if (host == NULL)
|
||||
return PyUnicode_FromString("");
|
||||
|
||||
ip = resolve_ip_callback_fn(host);
|
||||
|
||||
return PyUnicode_FromString(ip);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Context_geoip(PyObject *self, PyObject *args)
|
||||
{
|
||||
const char *ip;
|
||||
const char *countryCode;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s", &ip))
|
||||
return NULL;
|
||||
|
||||
if (ip == NULL)
|
||||
return PyUnicode_FromString("");
|
||||
|
||||
countryCode = geoip_callback_fn(ip);
|
||||
|
||||
return PyUnicode_FromString(countryCode);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Context_log(PyObject *self, PyObject *args)
|
||||
{
|
||||
const char *msg;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s", &msg))
|
||||
return NULL;
|
||||
|
||||
log_callback_fn(msg);
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
static PyMethodDef Context_methods[] = {
|
||||
{"resolve_ip", (PyCFunction) Context_resolve_ip, METH_VARARGS,
|
||||
"resolve_ip(host) -> string"
|
||||
},
|
||||
{"geoip", (PyCFunction) Context_geoip, METH_VARARGS,
|
||||
"geoip(ip) -> string"
|
||||
},
|
||||
{"log", (PyCFunction) Context_log, METH_VARARGS,
|
||||
"log(msg) -> void"
|
||||
},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyTypeObject ContextType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "clash.Context",
|
||||
.tp_doc = "Clash Context objects",
|
||||
.tp_basicsize = sizeof(ContextObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
|
||||
.tp_new = Context_new,
|
||||
.tp_init = (initproc) Context_init,
|
||||
.tp_dealloc = (destructor) Context_dealloc,
|
||||
.tp_traverse = (traverseproc) Context_traverse,
|
||||
.tp_clear = (inquiry) Context_clear,
|
||||
.tp_methods = Context_methods,
|
||||
.tp_getset = Context_getsetters,
|
||||
};
|
||||
|
||||
static PyModuleDef clashmodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
.m_name = "clash",
|
||||
.m_doc = "Clash module that creates an extension module for python3.",
|
||||
.m_size = -1,
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC
|
||||
PyInit_clash(void)
|
||||
{
|
||||
PyObject *m;
|
||||
|
||||
m = PyModule_Create(&clashmodule);
|
||||
if (m == NULL)
|
||||
return NULL;
|
||||
|
||||
if (PyType_Ready(&RuleProviderType) < 0)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&RuleProviderType);
|
||||
if (PyModule_AddObject(m, "RuleProvider", (PyObject *) &RuleProviderType) < 0) {
|
||||
Py_DECREF(&RuleProviderType);
|
||||
Py_DECREF(m);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (PyType_Ready(&ContextType) < 0)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&ContextType);
|
||||
if (PyModule_AddObject(m, "Context", (PyObject *) &ContextType) < 0) {
|
||||
Py_DECREF(&ContextType);
|
||||
Py_DECREF(m);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/* end Context objects */
|
||||
|
||||
/* --------------------------------------------------------------------- */
|
||||
|
||||
void
|
||||
append_inittab()
|
||||
{
|
||||
/* Add a built-in module, before Py_Initialize */
|
||||
PyImport_AppendInittab("clash", PyInit_clash);
|
||||
}
|
||||
|
||||
int new_clash_py_context(const char *provider_name_arr[], int size) {
|
||||
PyObject *dict = PyDict_New(); //Return value: New reference.
|
||||
if (dict == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"PyDict_New failure");
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
PyObject *rule_provider = RuleProvider_new(&RuleProviderType, NULL, NULL);
|
||||
if (rule_provider == NULL) {
|
||||
Py_DECREF(dict);
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"RuleProvider_new failure");
|
||||
return 0;
|
||||
}
|
||||
|
||||
RuleProviderObject *providerObj = (RuleProviderObject *) rule_provider;
|
||||
|
||||
PyObject *py_name = PyUnicode_FromString(provider_name_arr[i]); //Return value: New reference.
|
||||
RuleProvider_setname(providerObj, py_name, NULL);
|
||||
Py_DECREF(py_name);
|
||||
|
||||
PyDict_SetItemString(dict, provider_name_arr[i], rule_provider); //Parameter value: New reference.
|
||||
Py_DECREF(rule_provider);
|
||||
}
|
||||
|
||||
clash_context = Context_new(&ContextType, NULL, NULL);
|
||||
|
||||
if (clash_context == NULL) {
|
||||
Py_DECREF(dict);
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"Context_new failure");
|
||||
return 0;
|
||||
}
|
||||
|
||||
Context_setrule_providers((ContextObject *) clash_context, dict, NULL);
|
||||
Py_DECREF(dict);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *call_main(
|
||||
const char *type,
|
||||
const char *network,
|
||||
const char *process_name,
|
||||
const char *process_path,
|
||||
const char *host,
|
||||
const char *src_ip,
|
||||
unsigned short src_port,
|
||||
const char *dst_ip,
|
||||
unsigned short dst_port) {
|
||||
|
||||
PyObject *metadataDict;
|
||||
PyObject *tupleArgs;
|
||||
PyObject *result;
|
||||
|
||||
metadataDict = PyDict_New(); //Return value: New reference.
|
||||
|
||||
if (metadataDict == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"PyDict_New failure");
|
||||
return "-1";
|
||||
}
|
||||
|
||||
PyObject *p_type = PyUnicode_FromString(type); //Return value: New reference.
|
||||
PyObject *p_network = PyUnicode_FromString(network); //Return value: New reference.
|
||||
PyObject *p_process_name = PyUnicode_FromString(process_name); //Return value: New reference.
|
||||
PyObject *p_process_path = PyUnicode_FromString(process_path); //Return value: New reference.
|
||||
PyObject *p_host = PyUnicode_FromString(host); //Return value: New reference.
|
||||
PyObject *p_src_ip = PyUnicode_FromString(src_ip); //Return value: New reference.
|
||||
PyObject *p_src_port = PyLong_FromUnsignedLong((unsigned long)src_port); //Return value: New reference.
|
||||
PyObject *p_dst_ip = PyUnicode_FromString(dst_ip); //Return value: New reference.
|
||||
PyObject *p_dst_port = PyLong_FromUnsignedLong((unsigned long)dst_port); //Return value: New reference.
|
||||
|
||||
PyDict_SetItemString(metadataDict, "type", p_type); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "network", p_network); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "process_name", p_process_name); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "process_path", p_process_path); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "host", p_host); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "src_ip", p_src_ip); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "src_port", p_src_port); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "dst_ip", p_dst_ip); //Parameter value: New reference.
|
||||
PyDict_SetItemString(metadataDict, "dst_port", p_dst_port); //Parameter value: New reference.
|
||||
|
||||
Py_DECREF(p_type);
|
||||
Py_DECREF(p_network);
|
||||
Py_DECREF(p_process_name);
|
||||
Py_DECREF(p_process_path);
|
||||
Py_DECREF(p_host);
|
||||
Py_DECREF(p_src_ip);
|
||||
Py_DECREF(p_src_port);
|
||||
Py_DECREF(p_dst_ip);
|
||||
Py_DECREF(p_dst_port);
|
||||
|
||||
tupleArgs = PyTuple_New(2); //Return value: New reference.
|
||||
if (tupleArgs == NULL) {
|
||||
Py_DECREF(metadataDict);
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"PyTuple_New failure");
|
||||
return "-1";
|
||||
}
|
||||
|
||||
Py_INCREF(clash_context);
|
||||
PyTuple_SetItem(tupleArgs, 0, clash_context); //clash_context Parameter value: Stolen reference.
|
||||
PyTuple_SetItem(tupleArgs, 1, metadataDict); //metadataDict Parameter value: Stolen reference.
|
||||
|
||||
Py_INCREF(main_fn);
|
||||
result = PyObject_CallObject(main_fn, tupleArgs); //Return value: New reference.
|
||||
Py_DECREF(main_fn);
|
||||
Py_DECREF(tupleArgs);
|
||||
|
||||
if (result == NULL) {
|
||||
return "-1";
|
||||
}
|
||||
|
||||
if (!PyUnicode_Check(result)) {
|
||||
Py_DECREF(result);
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"script main function return value must be a string");
|
||||
return "-1";
|
||||
}
|
||||
|
||||
const char *adapter = PyUnicode_AsUTF8(result);
|
||||
|
||||
Py_DECREF(result);
|
||||
|
||||
return adapter;
|
||||
}
|
||||
|
||||
int call_shortcut(PyObject *shortcut_fn,
|
||||
const char *type,
|
||||
const char *network,
|
||||
const char *process_name,
|
||||
const char *process_path,
|
||||
const char *host,
|
||||
const char *src_ip,
|
||||
unsigned short src_port,
|
||||
const char *dst_ip,
|
||||
unsigned short dst_port) {
|
||||
|
||||
PyObject *args;
|
||||
PyObject *result;
|
||||
|
||||
args = Py_BuildValue("{s:O, s:s, s:s, s:s, s:s, s:s, s:H, s:s, s:H}",
|
||||
"ctx", clash_context,
|
||||
"network", network,
|
||||
"process_name", process_name,
|
||||
"process_path", process_path,
|
||||
"host", host,
|
||||
"src_ip", src_ip,
|
||||
"src_port", src_port,
|
||||
"dst_ip", dst_ip,
|
||||
"dst_port", dst_port); //Return value: New reference.
|
||||
|
||||
if (args == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"Py_BuildValue failure");
|
||||
return -1;
|
||||
}
|
||||
|
||||
PyObject *tupleArgs = PyTuple_New(0); //Return value: New reference.
|
||||
|
||||
Py_INCREF(clash_context);
|
||||
Py_INCREF(shortcut_fn);
|
||||
result = PyObject_Call(shortcut_fn, tupleArgs, args); //Return value: New reference.
|
||||
Py_DECREF(shortcut_fn);
|
||||
Py_DECREF(clash_context);
|
||||
Py_DECREF(tupleArgs);
|
||||
Py_DECREF(args);
|
||||
|
||||
if (result == NULL) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!PyBool_Check(result)) {
|
||||
Py_DECREF(result);
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"script shortcut return value must be as boolean");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int rs = (result == Py_True) ? 1 : 0;
|
||||
|
||||
Py_DECREF(result);
|
||||
|
||||
return rs;
|
||||
}
|
||||
|
||||
void finalize_Python() {
|
||||
Py_CLEAR(main_fn);
|
||||
Py_CLEAR(clash_context);
|
||||
Py_CLEAR(clash_module);
|
||||
Py_FinalizeEx();
|
||||
|
||||
clash_module = NULL;
|
||||
main_fn = NULL;
|
||||
clash_context = NULL;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------------- */
|
@ -1,338 +0,0 @@
|
||||
package script
|
||||
|
||||
/*
|
||||
#include "clash_module.h"
|
||||
|
||||
extern const char *resolveIPCallbackFn(const char *host);
|
||||
|
||||
void
|
||||
go_set_resolve_ip_callback() {
|
||||
set_resolve_ip_callback(resolveIPCallbackFn);
|
||||
}
|
||||
|
||||
extern const char *geoipCallbackFn(const char *ip);
|
||||
|
||||
void
|
||||
go_set_geoip_callback() {
|
||||
set_geoip_callback(geoipCallbackFn);
|
||||
}
|
||||
|
||||
extern const int ruleProviderCallbackFn(const char *provider_name, struct Metadata *metadata);
|
||||
|
||||
void
|
||||
go_set_rule_provider_callback() {
|
||||
set_rule_provider_callback(ruleProviderCallbackFn);
|
||||
}
|
||||
|
||||
extern void logCallbackFn(const char *msg);
|
||||
|
||||
void
|
||||
go_set_log_callback() {
|
||||
set_log_callback(logCallbackFn);
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
const ClashScriptModuleName = C.CLASH_SCRIPT_MODULE_NAME
|
||||
|
||||
var lock sync.Mutex
|
||||
|
||||
type PyObject C.PyObject
|
||||
|
||||
func togo(cobject *C.PyObject) *PyObject {
|
||||
return (*PyObject)(cobject)
|
||||
}
|
||||
|
||||
func toc(object *PyObject) *C.PyObject {
|
||||
return (*C.PyObject)(object)
|
||||
}
|
||||
|
||||
func (pyObject *PyObject) IncRef() {
|
||||
C.Py_IncRef(toc(pyObject))
|
||||
}
|
||||
|
||||
func (pyObject *PyObject) DecRef() {
|
||||
C.Py_DecRef(toc(pyObject))
|
||||
}
|
||||
|
||||
func (pyObject *PyObject) Clear() {
|
||||
C.py_clear(toc(pyObject))
|
||||
}
|
||||
|
||||
// Py_Initialize initialize Python3
|
||||
func Py_Initialize(program string, path string) error {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if C.Py_IsInitialized() != 0 {
|
||||
if pyThreadState != nil {
|
||||
PyEval_RestoreThread(pyThreadState)
|
||||
}
|
||||
C.finalize_Python()
|
||||
}
|
||||
|
||||
path = strings.ReplaceAll(path, "\\", "/")
|
||||
cPath := C.CString(path)
|
||||
|
||||
C.init_python(C.CString(program), cPath)
|
||||
err := PyLastError()
|
||||
|
||||
if err != nil {
|
||||
if C.Py_IsInitialized() != 0 {
|
||||
C.finalize_Python()
|
||||
_ = os.RemoveAll(constant.Path.ScriptDir())
|
||||
}
|
||||
return err
|
||||
} else if C.Py_IsInitialized() == 0 {
|
||||
err = errors.New("initialized script module failure")
|
||||
return err
|
||||
}
|
||||
|
||||
initPython3Callback()
|
||||
return nil
|
||||
}
|
||||
|
||||
func Py_IsInitialized() bool {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
return C.Py_IsInitialized() != 0
|
||||
}
|
||||
|
||||
func Py_Finalize() {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if C.Py_IsInitialized() != 0 {
|
||||
if pyThreadState != nil {
|
||||
PyEval_RestoreThread(pyThreadState)
|
||||
}
|
||||
C.finalize_Python()
|
||||
_ = os.RemoveAll(constant.Path.ScriptDir())
|
||||
log.Warnln("Clash clean up script mode.")
|
||||
}
|
||||
}
|
||||
|
||||
//Py_GetVersion get
|
||||
func Py_GetVersion() string {
|
||||
cversion := C.Py_GetVersion()
|
||||
return strings.Split(C.GoString(cversion), "\n")[0]
|
||||
}
|
||||
|
||||
// loadPyFunc loads a Python function by module and function name
|
||||
func loadPyFunc(moduleName, funcName string) (*C.PyObject, error) {
|
||||
// Convert names to C char*
|
||||
cMod := C.CString(moduleName)
|
||||
cFunc := C.CString(funcName)
|
||||
|
||||
// Free memory allocated by C.CString
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(cMod))
|
||||
C.free(unsafe.Pointer(cFunc))
|
||||
}()
|
||||
|
||||
fnc := C.load_func(cMod, cFunc)
|
||||
if fnc == nil {
|
||||
return nil, PyLastError()
|
||||
}
|
||||
|
||||
return fnc, nil
|
||||
}
|
||||
|
||||
//PyLastError python last error
|
||||
func PyLastError() error {
|
||||
cp := C.py_last_error()
|
||||
if cp == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New(C.GoString(cp))
|
||||
}
|
||||
|
||||
func LoadShortcutFunction(shortcut string) (*PyObject, error) {
|
||||
fnc, err := loadPyFunc(ClashScriptModuleName, shortcut)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return togo(fnc), nil
|
||||
}
|
||||
|
||||
func LoadMainFunction() error {
|
||||
C.load_main_func()
|
||||
err := PyLastError()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//CallPyMainFunction call python script main function
|
||||
//return the proxy adapter name.
|
||||
func CallPyMainFunction(mtd *constant.Metadata) (string, error) {
|
||||
_type := C.CString(mtd.Type.String())
|
||||
network := C.CString(mtd.NetWork.String())
|
||||
processName := C.CString(mtd.Process)
|
||||
processPath := C.CString(mtd.ProcessPath)
|
||||
host := C.CString(mtd.Host)
|
||||
|
||||
srcPortGo, _ := strconv.ParseUint(mtd.SrcPort, 10, 16)
|
||||
dstPortGo, _ := strconv.ParseUint(mtd.DstPort, 10, 16)
|
||||
srcPort := C.ushort(srcPortGo)
|
||||
dstPort := C.ushort(dstPortGo)
|
||||
|
||||
dstIpGo := ""
|
||||
srcIpGo := ""
|
||||
if mtd.SrcIP.IsValid() {
|
||||
srcIpGo = mtd.SrcIP.String()
|
||||
}
|
||||
if mtd.DstIP.IsValid() {
|
||||
dstIpGo = mtd.DstIP.String()
|
||||
}
|
||||
srcIp := C.CString(srcIpGo)
|
||||
dstIp := C.CString(dstIpGo)
|
||||
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(_type))
|
||||
C.free(unsafe.Pointer(network))
|
||||
C.free(unsafe.Pointer(processName))
|
||||
C.free(unsafe.Pointer(processPath))
|
||||
C.free(unsafe.Pointer(host))
|
||||
C.free(unsafe.Pointer(srcIp))
|
||||
C.free(unsafe.Pointer(dstIp))
|
||||
}()
|
||||
|
||||
runtime.LockOSThread()
|
||||
gilState := PyGILState_Ensure()
|
||||
defer PyGILState_Release(gilState)
|
||||
|
||||
cRs := C.call_main(_type, network, processName, processPath, host, srcIp, srcPort, dstIp, dstPort)
|
||||
|
||||
rs := C.GoString(cRs)
|
||||
if rs == "-1" {
|
||||
err := PyLastError()
|
||||
if err != nil {
|
||||
log.Errorln("[Script] script code error: %v", err)
|
||||
killSelf()
|
||||
return "", fmt.Errorf("script code error: %w", err)
|
||||
} else {
|
||||
return "", fmt.Errorf("script code error, result: %v", rs)
|
||||
}
|
||||
}
|
||||
|
||||
return rs, nil
|
||||
}
|
||||
|
||||
//CallPyShortcut call python script shortcuts function
|
||||
//param: shortcut name
|
||||
//return the match result.
|
||||
func CallPyShortcut(fn *PyObject, mtd *constant.Metadata) (bool, error) {
|
||||
_type := C.CString(mtd.Type.String())
|
||||
network := C.CString(mtd.NetWork.String())
|
||||
processName := C.CString(mtd.Process)
|
||||
processPath := C.CString(mtd.ProcessPath)
|
||||
host := C.CString(mtd.Host)
|
||||
|
||||
srcPortGo, _ := strconv.ParseUint(mtd.SrcPort, 10, 16)
|
||||
dstPortGo, _ := strconv.ParseUint(mtd.DstPort, 10, 16)
|
||||
srcPort := C.ushort(srcPortGo)
|
||||
dstPort := C.ushort(dstPortGo)
|
||||
|
||||
dstIpGo := ""
|
||||
srcIpGo := ""
|
||||
if mtd.SrcIP.IsValid() {
|
||||
srcIpGo = mtd.SrcIP.String()
|
||||
}
|
||||
if mtd.DstIP.IsValid() {
|
||||
dstIpGo = mtd.DstIP.String()
|
||||
}
|
||||
srcIp := C.CString(srcIpGo)
|
||||
dstIp := C.CString(dstIpGo)
|
||||
|
||||
defer func() {
|
||||
C.free(unsafe.Pointer(_type))
|
||||
C.free(unsafe.Pointer(network))
|
||||
C.free(unsafe.Pointer(processName))
|
||||
C.free(unsafe.Pointer(processPath))
|
||||
C.free(unsafe.Pointer(host))
|
||||
C.free(unsafe.Pointer(srcIp))
|
||||
C.free(unsafe.Pointer(dstIp))
|
||||
}()
|
||||
|
||||
runtime.LockOSThread()
|
||||
gilState := PyGILState_Ensure()
|
||||
defer PyGILState_Release(gilState)
|
||||
|
||||
cRs := C.call_shortcut(toc(fn), _type, network, processName, processPath, host, srcIp, srcPort, dstIp, dstPort)
|
||||
|
||||
rs := int(cRs)
|
||||
if rs == -1 {
|
||||
err := PyLastError()
|
||||
if err != nil {
|
||||
log.Errorln("[Script] script shortcut code error: %v", err)
|
||||
killSelf()
|
||||
return false, fmt.Errorf("script shortcut code error: %w", err)
|
||||
} else {
|
||||
return false, fmt.Errorf("script shortcut code error: result: %d", rs)
|
||||
}
|
||||
}
|
||||
|
||||
if rs == 1 {
|
||||
return true, nil
|
||||
} else {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func initPython3Callback() {
|
||||
C.go_set_resolve_ip_callback()
|
||||
C.go_set_geoip_callback()
|
||||
C.go_set_rule_provider_callback()
|
||||
C.go_set_log_callback()
|
||||
}
|
||||
|
||||
//NewClashPyContext new clash context for python
|
||||
func NewClashPyContext(ruleProvidersName []string) error {
|
||||
length := len(ruleProvidersName)
|
||||
cStringArr := make([]*C.char, length)
|
||||
for i, v := range ruleProvidersName {
|
||||
cStringArr[i] = C.CString(v)
|
||||
defer C.free(unsafe.Pointer(cStringArr[i]))
|
||||
}
|
||||
|
||||
cArrPointer := unsafe.Pointer(nil)
|
||||
if length > 0 {
|
||||
cArrPointer = unsafe.Pointer(&cStringArr[0])
|
||||
}
|
||||
|
||||
rs := C.new_clash_py_context((**C.char)(cArrPointer), C.int(length))
|
||||
|
||||
if int(rs) == 0 {
|
||||
err := PyLastError()
|
||||
return fmt.Errorf("new script module context failure: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func killSelf() {
|
||||
p, err := os.FindProcess(os.Getpid())
|
||||
if err != nil {
|
||||
os.Exit(int(syscall.SIGINT))
|
||||
return
|
||||
}
|
||||
_ = p.Signal(syscall.SIGINT)
|
||||
}
|
@ -1,65 +0,0 @@
|
||||
#ifndef CLASH_CALLBACK_MODULE_H__
|
||||
#define CLASH_CALLBACK_MODULE_H__
|
||||
|
||||
#include <Python.h>
|
||||
|
||||
#define CLASH_SCRIPT_MODULE_NAME "clash_script"
|
||||
|
||||
struct Metadata {
|
||||
const char *type; /* type socks5/http */
|
||||
const char *network; /* network tcp/udp */
|
||||
const char *process_name;
|
||||
const char *process_path;
|
||||
const char *host;
|
||||
const char *src_ip;
|
||||
unsigned short src_port;
|
||||
const char *dst_ip;
|
||||
unsigned short dst_port;
|
||||
};
|
||||
|
||||
/** callback function, that call go function by python3 script. **/
|
||||
typedef const char *(*resolve_ip_callback)(const char *host);
|
||||
typedef const char *(*geoip_callback)(const char *ip);
|
||||
typedef const int (*rule_provider_callback)(const char *provider_name, struct Metadata *metadata);
|
||||
typedef void (*log_callback)(const char *msg);
|
||||
|
||||
void set_resolve_ip_callback(resolve_ip_callback cb);
|
||||
void set_geoip_callback(geoip_callback cb);
|
||||
void set_rule_provider_callback(rule_provider_callback cb);
|
||||
void set_log_callback(log_callback cb);
|
||||
/*---------------------------------------------------------------*/
|
||||
|
||||
void append_inittab();
|
||||
void init_python(const char *program, const char *path);
|
||||
void load_main_func();
|
||||
void finalize_Python();
|
||||
void py_clear(PyObject *obj);
|
||||
const char *py_last_error();
|
||||
|
||||
PyObject *load_func(const char *module_name, char *func_name);
|
||||
|
||||
int new_clash_py_context(const char *provider_name_arr[], int size);
|
||||
|
||||
const char *call_main(
|
||||
const char *type,
|
||||
const char *network,
|
||||
const char *process_name,
|
||||
const char *process_path,
|
||||
const char *host,
|
||||
const char *src_ip,
|
||||
unsigned short src_port,
|
||||
const char *dst_ip,
|
||||
unsigned short dst_port);
|
||||
|
||||
int call_shortcut(PyObject *shortcut_fn,
|
||||
const char *type,
|
||||
const char *network,
|
||||
const char *process_name,
|
||||
const char *process_path,
|
||||
const char *host,
|
||||
const char *src_ip,
|
||||
unsigned short src_port,
|
||||
const char *dst_ip,
|
||||
unsigned short dst_port);
|
||||
|
||||
#endif // CLASH_CALLBACK_MODULE_H__
|
@ -1,145 +0,0 @@
|
||||
package script
|
||||
|
||||
/*
|
||||
#include "clash_module.h"
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/clash/component/mmdb"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
"github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
var (
|
||||
ruleProviders = map[string]constant.Rule{}
|
||||
pyThreadState *PyThreadState
|
||||
)
|
||||
|
||||
func UpdateRuleProviders(rpd map[string]constant.Rule) {
|
||||
ruleProviders = rpd
|
||||
if Py_IsInitialized() {
|
||||
pyThreadState = PyEval_SaveThread()
|
||||
}
|
||||
}
|
||||
|
||||
//export resolveIPCallbackFn
|
||||
func resolveIPCallbackFn(cHost *C.char) *C.char {
|
||||
host := C.GoString(cHost)
|
||||
if len(host) == 0 {
|
||||
cip := C.CString("")
|
||||
defer C.free(unsafe.Pointer(cip))
|
||||
return cip
|
||||
}
|
||||
if ip, err := resolver.ResolveIP(host); err == nil {
|
||||
cip := C.CString(ip.String())
|
||||
defer C.free(unsafe.Pointer(cip))
|
||||
return cip
|
||||
} else {
|
||||
log.Errorln("[Script] resolve ip error: %s", err.Error())
|
||||
cip := C.CString("")
|
||||
defer C.free(unsafe.Pointer(cip))
|
||||
return cip
|
||||
}
|
||||
}
|
||||
|
||||
//export geoipCallbackFn
|
||||
func geoipCallbackFn(cIP *C.char) *C.char {
|
||||
dstIP, err := netip.ParseAddr(C.GoString(cIP))
|
||||
|
||||
if err != nil {
|
||||
emptyC := C.CString("")
|
||||
defer C.free(unsafe.Pointer(emptyC))
|
||||
|
||||
return emptyC
|
||||
}
|
||||
|
||||
if dstIP.IsPrivate() ||
|
||||
dstIP.IsUnspecified() ||
|
||||
dstIP.IsLoopback() ||
|
||||
dstIP.IsMulticast() ||
|
||||
dstIP.IsLinkLocalUnicast() ||
|
||||
resolver.IsFakeBroadcastIP(dstIP) {
|
||||
|
||||
lanC := C.CString("LAN")
|
||||
defer C.free(unsafe.Pointer(lanC))
|
||||
|
||||
return lanC
|
||||
}
|
||||
|
||||
record, _ := mmdb.Instance().Country(dstIP.AsSlice())
|
||||
|
||||
rc := C.CString(strings.ToUpper(record.Country.IsoCode))
|
||||
defer C.free(unsafe.Pointer(rc))
|
||||
|
||||
return rc
|
||||
}
|
||||
|
||||
//export ruleProviderCallbackFn
|
||||
func ruleProviderCallbackFn(cProviderName *C.char, cMetadata *C.struct_Metadata) C.int {
|
||||
//_type := C.GoString(cMetadata._type)
|
||||
//network := C.GoString(cMetadata.network)
|
||||
processName := C.GoString(cMetadata.process_name)
|
||||
processPath := C.GoString(cMetadata.process_path)
|
||||
host := C.GoString(cMetadata.host)
|
||||
srcIp := C.GoString(cMetadata.src_ip)
|
||||
srcPort := strconv.Itoa(int(cMetadata.src_port))
|
||||
dstIp := C.GoString(cMetadata.dst_ip)
|
||||
dstPort := strconv.Itoa(int(cMetadata.dst_port))
|
||||
|
||||
addrType := constant.AtypDomainName
|
||||
if h, err := netip.ParseAddr(host); err == nil {
|
||||
if h.Is4() {
|
||||
addrType = constant.AtypIPv4
|
||||
} else {
|
||||
addrType = constant.AtypIPv6
|
||||
}
|
||||
}
|
||||
|
||||
src, _ := netip.ParseAddr(srcIp)
|
||||
dst, _ := netip.ParseAddr(dstIp)
|
||||
|
||||
metadata := &constant.Metadata{
|
||||
AddrType: addrType,
|
||||
SrcIP: src,
|
||||
DstIP: dst,
|
||||
SrcPort: srcPort,
|
||||
DstPort: dstPort,
|
||||
Host: host,
|
||||
Process: processName,
|
||||
ProcessPath: processPath,
|
||||
}
|
||||
|
||||
providerName := C.GoString(cProviderName)
|
||||
|
||||
rule, ok := ruleProviders[providerName]
|
||||
if !ok {
|
||||
log.Warnln("[Script] rule provider [%s] not found", providerName)
|
||||
return C.int(0)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(providerName, "geosite:") {
|
||||
if len(host) == 0 {
|
||||
return C.int(0)
|
||||
}
|
||||
metadata.AddrType = constant.AtypDomainName
|
||||
}
|
||||
|
||||
rs := rule.Match(metadata)
|
||||
|
||||
if rs {
|
||||
return C.int(1)
|
||||
}
|
||||
return C.int(0)
|
||||
}
|
||||
|
||||
//export logCallbackFn
|
||||
func logCallbackFn(msg *C.char) {
|
||||
|
||||
log.Infoln(C.GoString(msg))
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
package script
|
||||
|
||||
/*
|
||||
#include "Python.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
//PyThreadState : https://docs.python.org/3/c-api/init.html#c.PyThreadState
|
||||
type PyThreadState C.PyThreadState
|
||||
|
||||
//PyGILState is an opaque “handle” to the thread state when PyGILState_Ensure() was called, and must be passed to PyGILState_Release() to ensure Python is left in the same state
|
||||
type PyGILState C.PyGILState_STATE
|
||||
|
||||
//PyEval_SaveThread : https://docs.python.org/3/c-api/init.html#c.PyEval_SaveThread
|
||||
func PyEval_SaveThread() *PyThreadState {
|
||||
return (*PyThreadState)(C.PyEval_SaveThread())
|
||||
}
|
||||
|
||||
//PyEval_RestoreThread : https://docs.python.org/3/c-api/init.html#c.PyEval_RestoreThread
|
||||
func PyEval_RestoreThread(tstate *PyThreadState) {
|
||||
C.PyEval_RestoreThread((*C.PyThreadState)(tstate))
|
||||
}
|
||||
|
||||
//PyThreadState_Get : https://docs.python.org/3/c-api/init.html#c.PyThreadState_Get
|
||||
func PyThreadState_Get() *PyThreadState {
|
||||
return (*PyThreadState)(C.PyThreadState_Get())
|
||||
}
|
||||
|
||||
//PyThreadState_Swap : https://docs.python.org/3/c-api/init.html#c.PyThreadState_Swap
|
||||
func PyThreadState_Swap(tstate *PyThreadState) *PyThreadState {
|
||||
return (*PyThreadState)(C.PyThreadState_Swap((*C.PyThreadState)(tstate)))
|
||||
}
|
||||
|
||||
//PyGILState_Ensure : https://docs.python.org/3/c-api/init.html#c.PyGILState_Ensure
|
||||
func PyGILState_Ensure() PyGILState {
|
||||
return PyGILState(C.PyGILState_Ensure())
|
||||
}
|
||||
|
||||
//PyGILState_Release : https://docs.python.org/3/c-api/init.html#c.PyGILState_Release
|
||||
func PyGILState_Release(state PyGILState) {
|
||||
C.PyGILState_Release(C.PyGILState_STATE(state))
|
||||
}
|
||||
|
||||
//PyGILState_GetThisThreadState : https://docs.python.org/3/c-api/init.html#c.PyGILState_GetThisThreadState
|
||||
func PyGILState_GetThisThreadState() *PyThreadState {
|
||||
return (*PyThreadState)(C.PyGILState_GetThisThreadState())
|
||||
}
|
||||
|
||||
//PyGILState_Check : https://docs.python.org/3/c-api/init.html#c.PyGILState_Check
|
||||
func PyGILState_Check() bool {
|
||||
return C.PyGILState_Check() == 1
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user