Compare commits
299 Commits
Author | SHA1 | Date | |
---|---|---|---|
5b7f0de48b | |||
a5b950a779 | |||
a2d59d6ef5 | |||
8ef5cdb8be | |||
c7b718f651 | |||
ff56e5c5de | |||
661c417fce | |||
7d20097465 | |||
a20b9a3960 | |||
e0d3f926b7 | |||
121bc910f6 | |||
4522cdc551 | |||
410772e81c | |||
0267b2efad | |||
c6d375eda2 | |||
847f41952e | |||
47044ec0d8 | |||
426ca36118 | |||
571d2a0075 | |||
1be09f5751 | |||
2663cb2e6e | |||
9b0bbb90ff | |||
588645a2c3 | |||
1bfebd0d03 | |||
3705996974 | |||
09697b7679 | |||
4578b2c826 | |||
b3a293ab07 | |||
507ba16065 | |||
aa9f8a39a3 | |||
8d37220566 | |||
53e17a916b | |||
247dd84970 | |||
c2f3111922 | |||
44872300e9 | |||
91ed0118f6 | |||
a461c2306a | |||
46f4f84442 | |||
250a9f4f84 | |||
b4292d0972 | |||
d755383e39 | |||
dff1e8f1ce | |||
995aa7a8fc | |||
3ca5d17c40 | |||
244cb370a4 | |||
c35cb24bda | |||
b6ff08074c | |||
70d53fd45a | |||
f231a63e93 | |||
6091fcdfec | |||
bcfc15e398 | |||
045edc188c | |||
0778591524 | |||
d5e52bed43 | |||
06fdd3abe0 | |||
4e5898197a | |||
f96ebab99f | |||
3c54f99fea | |||
824f5bd731 | |||
3f3db8476e | |||
f375f080da | |||
e19e9ef5a4 | |||
682e65cb54 | |||
16a6d409d9 | |||
4186bcf1b2 | |||
df5112175f | |||
d9341a49ea | |||
4e9e4b6cde | |||
936b7012ba | |||
a9cbd9ec98 | |||
c9943fb857 | |||
a40274e2a2 | |||
b59d45c660 | |||
7b01e103c2 | |||
93a8acecce | |||
586bb91c0c | |||
baf03b81e3 | |||
9807e1189c | |||
3d5a0d9f73 | |||
cc96187f58 | |||
3aefa1d924 | |||
42e21b3733 | |||
0a35237915 | |||
a1f3a5ea26 | |||
e63f995258 | |||
d0c829c578 | |||
4ad9761b32 | |||
1f593d37fb | |||
109bfcb0f9 | |||
7ee49f5171 | |||
d759d16944 | |||
807d53c1e7 | |||
1355196b7c | |||
573316bcde | |||
784c28266c | |||
5da1b2a8aa | |||
0976d27cb1 | |||
6c83ff3496 | |||
f7f97ef625 | |||
5acdd72a1d | |||
f53686103d | |||
f63c9eb22f | |||
a37243cf30 | |||
b3c1b4a840 | |||
14bbf6eedc | |||
aa81193d5b | |||
9eb98e399d | |||
d48cfecf60 | |||
6036fb63ba | |||
cd48f69b1f | |||
fcc594ae26 | |||
f4de055aa1 | |||
35925cb3da | |||
ff430df845 | |||
e4cdea2111 | |||
b6ee47a541 | |||
b25009cde7 | |||
6fedd7ec84 | |||
9619c3fb20 | |||
02d029dd2d | |||
09c28e0355 | |||
3600077f3b | |||
de7656a787 | |||
5dfe7f8561 | |||
ed27898a33 | |||
532396d25c | |||
4b1b494164 | |||
0d33dc3eb9 | |||
994cbff215 | |||
bea2ee8bf2 | |||
1e5593f1a9 | |||
34febc4579 | |||
97581148b5 | |||
0402878daa | |||
4735f61fd1 | |||
16ae107e70 | |||
83efe2ae57 | |||
87e4d94290 | |||
b98e9ea202 | |||
9a62b1081d | |||
2cd1b890ce | |||
ba060bd0ee | |||
b1795b1e3d | |||
76c9820065 | |||
2db4ce57ef | |||
50b3d497f6 | |||
2321e9139d | |||
baabf21340 | |||
d3bb4c65a8 | |||
8c3e2a7559 | |||
bc52f8e4fd | |||
d3b14c325f | |||
4859b158b4 | |||
d65b51c62b | |||
a6444bb449 | |||
e09931dcf7 | |||
5bd189f2d0 | |||
8766287e72 | |||
10f9571c9e | |||
96a8259c42 | |||
68dd0622b8 | |||
558ac6b965 | |||
e773f95f21 | |||
314ce1c249 | |||
13275b1aa6 | |||
02d9169b5d | |||
7631bcc99e | |||
a32ee13fc9 | |||
b8ed738238 | |||
687c2a21cf | |||
ad18064e6b | |||
c9735ef75b | |||
b70882f01a | |||
5805334ccd | |||
c1b4382fe8 | |||
008743f20b | |||
50d778da3c | |||
8b7c731fd6 | |||
0b7918de9c | |||
4f61c04519 | |||
89cf06036d | |||
4ba6f248bc | |||
83a684c551 | |||
92a23f1eab | |||
622ac45258 | |||
791d203b5f | |||
77d6f9ae6f | |||
b1d9dfd6bf | |||
6532947e71 | |||
6c5f23f552 | |||
78c3034158 | |||
8f0098092d | |||
33a6579a3a | |||
b4221d4b74 | |||
0e4b9daaad | |||
ee72865f48 | |||
6521acf8f1 | |||
4f73410618 | |||
20eff200b1 | |||
ae1e1dc9f6 | |||
cf9e1545a4 | |||
6c7a8fffe0 | |||
3a3e2c05af | |||
02c7fd8d70 | |||
e6aa452b51 | |||
35449bfa17 | |||
acd51bbc90 | |||
f44cd9180c | |||
93c987a6cb | |||
3f0584ac09 | |||
59968fff1c | |||
7c62fe41b4 | |||
2781090405 | |||
14c9cf1b97 | |||
3dfff84cc3 | |||
5f3db72422 | |||
18bb285a90 | |||
60bad66bc3 | |||
99b34e8d8b | |||
9f1d85ab6e | |||
4323dd24d0 | |||
59bda1d547 | |||
1c760935f4 | |||
4f674755ce | |||
f1b792bd26 | |||
58c077b45e | |||
1854199c47 | |||
ecac8eb8e5 | |||
48cff50a4c | |||
fb628e9c62 | |||
2dece02df6 | |||
8f32e6a60f | |||
98614a1f3f | |||
c1b4c94b9c | |||
7ddbc12cdb | |||
1a217e21e9 | |||
147a7ce779 | |||
fb0289bb4c | |||
3e7970612a | |||
46244a6496 | |||
71d30e6654 | |||
008731c249 | |||
5628f97da1 | |||
8d0c6c6e66 | |||
5073c3cde8 | |||
3a27cfc4a1 | |||
3638b077cd | |||
646bd4eeb4 | |||
752f87a8dc | |||
b979ff0bc2 | |||
b085addbb0 | |||
94e0e4b000 | |||
7d51ab5846 | |||
41a9488cfa | |||
51b6b8521b | |||
e5379558f6 | |||
d1fd57c432 | |||
18603c9a46 | |||
5036f62a9c | |||
2047b8eda1 | |||
0e56c195bb | |||
2b33bfae6b | |||
3fc6d55003 | |||
8eddcd77bf | |||
27dd1d7944 | |||
b1cf2ec837 | |||
84f627f302 | |||
5c03613858 | |||
1825535abd | |||
2750c7ead0 | |||
3ccd7def86 | |||
65dab4e34f | |||
5591e15452 | |||
19f809b1c8 | |||
206767247e | |||
518354e7eb | |||
86dfb6562c | |||
c0a2473160 | |||
70a19b999d | |||
e54f51af81 | |||
b068466108 | |||
b562f28c1b | |||
230e01f078 | |||
082847b403 | |||
9471d80785 | |||
b263095533 | |||
14d5137703 | |||
d8a771916a | |||
f7f30d3406 | |||
b2c9cbb43e | |||
c733f80793 | |||
88d8f93793 | |||
e57a13ed7a | |||
23525ecc15 | |||
814bd05315 | |||
e81b88fb94 | |||
c4994d6429 | |||
0740d20ba0 | |||
9eaca6e4ab |
96
.github/ISSUE_TEMPLATE/bug_report.md
vendored
96
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@ -1,96 +0,0 @@
|
|||||||
---
|
|
||||||
name: Bug report
|
|
||||||
about: Create a report to help us improve
|
|
||||||
title: "[Bug]"
|
|
||||||
labels: ''
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
<!-- The English version is available. -->
|
|
||||||
感谢你向 Clash Core 提交 issue!
|
|
||||||
在提交之前,请确认:
|
|
||||||
|
|
||||||
- [ ] 我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
|
||||||
- [ ] 这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 Openclash、Koolclash 等)的特定问题
|
|
||||||
- [ ] 我已经使用 Clash core 的 dev 分支版本测试过,问题依旧存在
|
|
||||||
- [ ] 如果你可以自己 debug 并解决的话,提交 PR 吧!
|
|
||||||
|
|
||||||
请注意,如果你并没有遵照这个 issue template 填写内容,我们将直接关闭这个 issue。
|
|
||||||
|
|
||||||
<!--
|
|
||||||
Thanks for submitting an issue towards the Clash core!
|
|
||||||
But before so, please do the following checklist:
|
|
||||||
|
|
||||||
- [ ] Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
|
||||||
- [ ] Your issue may already be reported! Please search on the [issue tracker](……/) before creating one.
|
|
||||||
- [ ] I have tested using the dev branch, and the issue still exists.
|
|
||||||
- [ ] This is an issue related to the Clash core, not to the derivatives of Clash, like Openclash or Koolclash
|
|
||||||
|
|
||||||
Please understand that we close issues that fail to follow the issue template.
|
|
||||||
-->
|
|
||||||
|
|
||||||
我都确认过了,我要继续提交。
|
|
||||||
<!-- None of the above, create a bug report -->
|
|
||||||
------------------------------------------------------------------
|
|
||||||
|
|
||||||
请附上任何可以帮助我们解决这个问题的信息,如果我们收到的信息不足,我们将对这个 issue 加上 *Needs more information* 标记并在收到更多资讯之前关闭 issue。
|
|
||||||
<!-- Make sure to add **all the information needed to understand the bug** so that someone can help. If the info is missing we'll add the 'Needs more information' label and close the issue until there is enough information. -->
|
|
||||||
|
|
||||||
### clash core config
|
|
||||||
<!--
|
|
||||||
在下方附上 Clash core 脱敏后配置文件的内容
|
|
||||||
Paste the Clash core configuration below.
|
|
||||||
-->
|
|
||||||
```
|
|
||||||
……
|
|
||||||
```
|
|
||||||
|
|
||||||
### Clash log
|
|
||||||
<!--
|
|
||||||
在下方附上 Clash Core 的日志,log level 最好使用 DEBUG
|
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
|
||||||
-->
|
|
||||||
```
|
|
||||||
……
|
|
||||||
```
|
|
||||||
|
|
||||||
### 环境 Environment
|
|
||||||
|
|
||||||
* Clash Core 的操作系统 (the OS that the Clash core is running on)
|
|
||||||
……
|
|
||||||
* 使用者的操作系统 (the OS running on the client)
|
|
||||||
……
|
|
||||||
* 网路环境或拓扑 (network conditions/topology)
|
|
||||||
……
|
|
||||||
* iptables,如果适用 (if applicable)
|
|
||||||
……
|
|
||||||
* ISP 有没有进行 DNS 污染 (is your ISP performing DNS pollution?)
|
|
||||||
……
|
|
||||||
* 其他
|
|
||||||
……
|
|
||||||
|
|
||||||
### 说明 Description
|
|
||||||
|
|
||||||
<!--
|
|
||||||
请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?
|
|
||||||
-->
|
|
||||||
|
|
||||||
### 重现问题的具体布骤 Steps to Reproduce
|
|
||||||
|
|
||||||
1. [First Step]
|
|
||||||
2. [Second Step]
|
|
||||||
3. ……
|
|
||||||
|
|
||||||
**我预期会发生……?**
|
|
||||||
<!-- **Expected behavior:** [What you expected to happen] -->
|
|
||||||
|
|
||||||
**实际上发生了什麽?**
|
|
||||||
<!-- **Actual behavior:** [What actually happened] -->
|
|
||||||
|
|
||||||
### 可能的解决方案 Possible Solution
|
|
||||||
<!-- 此项非必须,但是如果你有想法的话欢迎提出。 -->
|
|
||||||
<!-- Not obligatory, but suggest a fix/reason for the bug, -->
|
|
||||||
<!-- or ideas how to implement the addition or change -->
|
|
||||||
|
|
||||||
### 更多信息 More Information
|
|
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
name: Bug report
|
||||||
|
description: Create a report to help us improve
|
||||||
|
title: "[Bug] "
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Verify steps
|
||||||
|
description: "
|
||||||
|
在提交之前,请确认
|
||||||
|
Please verify that you've followed these steps
|
||||||
|
"
|
||||||
|
options:
|
||||||
|
- label: "
|
||||||
|
如果你可以自己 debug 并解决的话,提交 PR 吧
|
||||||
|
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
||||||
|
I have searched on the [issue tracker](……/) for a related issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经使用 dev 分支版本测试过,问题依旧存在
|
||||||
|
I have tested using the dev branch, and the issue still exists.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
||||||
|
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
||||||
|
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
attributes:
|
||||||
|
label: Clash version
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: What OS are you seeing the problem on?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- macOS
|
||||||
|
- Windows
|
||||||
|
- Linux
|
||||||
|
- OpenBSD/FreeBSD
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: yaml
|
||||||
|
label: "Clash config"
|
||||||
|
description: "
|
||||||
|
在下方附上 Clash core 脱敏后配置文件的内容
|
||||||
|
Paste the Clash core configuration below.
|
||||||
|
"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: shell
|
||||||
|
label: Clash log
|
||||||
|
description: "
|
||||||
|
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
||||||
|
Paste the Clash core log below with the log level set to `DEBUG`.
|
||||||
|
"
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
validations:
|
||||||
|
required: true
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
6
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
|
||||||
|
contact_links:
|
||||||
|
- name: Get help in GitHub Discussions
|
||||||
|
url: https://github.com/Dreamacro/clash/discussions
|
||||||
|
about: Have a question? Not sure if your issue affects everyone reproducibly? The quickest way to get help is on Clash's GitHub Discussions!
|
78
.github/ISSUE_TEMPLATE/feature_request.md
vendored
78
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -1,78 +0,0 @@
|
|||||||
---
|
|
||||||
name: Feature request
|
|
||||||
about: Suggest an idea for this project
|
|
||||||
title: "[Feature]"
|
|
||||||
labels: ''
|
|
||||||
assignees: ''
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
<!-- The English version is available. -->
|
|
||||||
感谢你向 Clash Core 提交 Feature Request!
|
|
||||||
在提交之前,请确认:
|
|
||||||
|
|
||||||
- [ ] 我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
|
||||||
|
|
||||||
请注意,如果你并没有遵照这个 issue template 填写内容,我们将直接关闭这个 issue。
|
|
||||||
|
|
||||||
<!--
|
|
||||||
Thanks for submitting a feature request towards the Clash core!
|
|
||||||
But before so, please do the following checklist:
|
|
||||||
|
|
||||||
- [ ] I have searched on the [issue tracker](……/) before creating the issue.
|
|
||||||
|
|
||||||
Please understand that we close issues that fail to follow the issue template.
|
|
||||||
-->
|
|
||||||
|
|
||||||
我都确认过了,我要继续提交。
|
|
||||||
<!-- None of the above, create a feature request -->
|
|
||||||
------------------------------------------------------------------
|
|
||||||
|
|
||||||
请附上任何可以帮助我们解决这个问题的信息,如果我们收到的信息不足,我们将对这个 issue 加上 *Needs more information* 标记并在收到更多资讯之前关闭 issue。
|
|
||||||
<!-- Make sure to add **all the information needed to understand the bug** so that someone can help. If the info is missing we'll add the 'Needs more information' label and close the issue until there is enough information. -->
|
|
||||||
|
|
||||||
### Clash core config
|
|
||||||
<!--
|
|
||||||
在下方附上 Clash Core 脱敏后的配置内容
|
|
||||||
Paste the Clash core configuration below.
|
|
||||||
-->
|
|
||||||
```
|
|
||||||
……
|
|
||||||
```
|
|
||||||
|
|
||||||
### Clash log
|
|
||||||
<!--
|
|
||||||
在下方附上 Clash Core 的日志,log level 请使用 DEBUG
|
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
|
||||||
-->
|
|
||||||
```
|
|
||||||
……
|
|
||||||
```
|
|
||||||
|
|
||||||
### 环境 Environment
|
|
||||||
|
|
||||||
* Clash Core 的操作系统 (the OS that the Clash core is running on)
|
|
||||||
……
|
|
||||||
* 使用者的操作系统 (the OS running on the client)
|
|
||||||
……
|
|
||||||
* 网路环境或拓扑 (network conditions/topology)
|
|
||||||
……
|
|
||||||
* iptables,如果适用 (if applicable)
|
|
||||||
……
|
|
||||||
* ISP 有没有进行 DNS 污染 (is your ISP performing DNS pollution?)
|
|
||||||
……
|
|
||||||
* 其他
|
|
||||||
……
|
|
||||||
|
|
||||||
### 说明 Description
|
|
||||||
|
|
||||||
<!--
|
|
||||||
请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
|
||||||
-->
|
|
||||||
|
|
||||||
### 可能的解决方案 Possible Solution
|
|
||||||
<!-- 此项非必须,但是如果你有想法的话欢迎提出。 -->
|
|
||||||
<!-- Not obligatory, but suggest a fix/reason for the bug, -->
|
|
||||||
<!-- or ideas how to implement the addition or change -->
|
|
||||||
|
|
||||||
### 更多信息 More Information
|
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
title: "[Feature] "
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Verify steps
|
||||||
|
description: "
|
||||||
|
在提交之前,请确认
|
||||||
|
Please verify that you've followed these steps
|
||||||
|
"
|
||||||
|
options:
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
||||||
|
I have searched on the [issue tracker](……/) for a related feature request.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
||||||
|
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Possible Solution
|
||||||
|
description: "
|
||||||
|
此项非必须,但是如果你有想法的话欢迎提出。
|
||||||
|
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
||||||
|
"
|
30
.github/workflows/codeql-analysis.yml
vendored
Normal file
30
.github/workflows/codeql-analysis.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
name: "CodeQL"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ master, dev ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'go' ]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- 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
|
76
.github/workflows/docker.yml
vendored
Normal file
76
.github/workflows/docker.yml
vendored
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
name: Publish Docker Image
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
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/v7,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
||||||
|
|
||||||
|
- name: Get all docker tags
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
uses: actions/github-script@v4
|
||||||
|
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/v7,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: ${{steps.tags.outputs.result}}
|
18
.github/workflows/go.yml
vendored
18
.github/workflows/go.yml
vendored
@ -7,24 +7,27 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v1
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
go-version: 1.13.x
|
go-version: 1.17
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v1
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Cache go module
|
- name: Cache go module
|
||||||
uses: actions/cache@v1
|
uses: actions/cache@v2
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-go-
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
- name: Get dependencies and run test
|
- name: Get dependencies, run test and static check
|
||||||
run: |
|
run: |
|
||||||
go test ./...
|
go test ./...
|
||||||
|
go vet ./...
|
||||||
|
go install honnef.co/go/tools/cmd/staticcheck@latest
|
||||||
|
staticcheck -- $(go list ./...)
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
@ -36,9 +39,6 @@ jobs:
|
|||||||
- name: Upload Release
|
- name: Upload Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
with:
|
||||||
files: bin/*
|
files: bin/*
|
||||||
draft: true
|
draft: true
|
||||||
prerelease: true
|
|
||||||
|
18
.github/workflows/stale.yml
vendored
Normal file
18
.github/workflows/stale.yml
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
|
||||||
|
name: Mark stale issues and pull requests
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "30 1 * * *"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
stale:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/stale@v4
|
||||||
|
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
|
@ -3,12 +3,14 @@ FROM golang:alpine as builder
|
|||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache make git && \
|
||||||
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
||||||
WORKDIR /clash-src
|
WORKDIR /clash-src
|
||||||
|
COPY --from=tonistiigi/xx:golang / /
|
||||||
COPY . /clash-src
|
COPY . /clash-src
|
||||||
RUN go mod download && \
|
RUN go mod download && \
|
||||||
make linux-amd64 && \
|
make docker && \
|
||||||
mv ./bin/clash-linux-amd64 /clash
|
mv ./bin/clash-docker /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
|
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates
|
RUN apk add --no-cache ca-certificates
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
|
@ -1,20 +0,0 @@
|
|||||||
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 && \
|
|
||||||
wget -O /qemu-arm-static https://github.com/multiarch/qemu-user-static/releases/latest/download/qemu-arm-static && \
|
|
||||||
chmod +x /qemu-arm-static
|
|
||||||
|
|
||||||
WORKDIR /clash-src
|
|
||||||
COPY . /clash-src
|
|
||||||
RUN go mod download && \
|
|
||||||
make linux-armv7 && \
|
|
||||||
mv ./bin/clash-linux-armv7 /clash
|
|
||||||
|
|
||||||
FROM arm32v7/alpine:latest
|
|
||||||
|
|
||||||
COPY --from=builder /qemu-arm-static /usr/bin/
|
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
|
||||||
COPY --from=builder /clash /
|
|
||||||
RUN apk add --no-cache ca-certificates
|
|
||||||
ENTRYPOINT ["/clash"]
|
|
@ -1,20 +0,0 @@
|
|||||||
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 && \
|
|
||||||
wget -O /qemu-aarch64-static https://github.com/multiarch/qemu-user-static/releases/latest/download/qemu-aarch64-static && \
|
|
||||||
chmod +x /qemu-aarch64-static
|
|
||||||
|
|
||||||
WORKDIR /clash-src
|
|
||||||
COPY . /clash-src
|
|
||||||
RUN go mod download && \
|
|
||||||
make linux-armv8 && \
|
|
||||||
mv ./bin/clash-linux-armv8 /clash
|
|
||||||
|
|
||||||
FROM arm64v8/alpine:latest
|
|
||||||
|
|
||||||
COPY --from=builder /qemu-aarch64-static /usr/bin/
|
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
|
||||||
COPY --from=builder /clash /
|
|
||||||
RUN apk add --no-cache ca-certificates
|
|
||||||
ENTRYPOINT ["/clash"]
|
|
27
Makefile
27
Makefile
@ -2,12 +2,13 @@ NAME=clash
|
|||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
VERSION=$(shell git describe --tags || echo "unknown version")
|
VERSION=$(shell git describe --tags || echo "unknown version")
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s'
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
|
darwin-arm64 \
|
||||||
linux-386 \
|
linux-386 \
|
||||||
linux-amd64 \
|
linux-amd64 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
@ -21,17 +22,26 @@ PLATFORM_LIST = \
|
|||||||
linux-mips64 \
|
linux-mips64 \
|
||||||
linux-mips64le \
|
linux-mips64le \
|
||||||
freebsd-386 \
|
freebsd-386 \
|
||||||
freebsd-amd64
|
freebsd-amd64 \
|
||||||
|
freebsd-arm64
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-386 \
|
||||||
windows-amd64
|
windows-amd64 \
|
||||||
|
windows-arm64 \
|
||||||
|
windows-arm32v7
|
||||||
|
|
||||||
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||||
|
|
||||||
|
docker:
|
||||||
|
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-arm64:
|
||||||
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -74,12 +84,21 @@ freebsd-386:
|
|||||||
freebsd-amd64:
|
freebsd-amd64:
|
||||||
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-arm64:
|
||||||
|
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows $(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))
|
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
||||||
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
||||||
|
|
||||||
|
311
README.md
311
README.md
@ -19,303 +19,39 @@
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Local HTTP/HTTPS/SOCKS server
|
- Local HTTP/HTTPS/SOCKS server with authentication support
|
||||||
- GeoIP rule support
|
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
||||||
- Supports Vmess, Shadowsocks, Snell and SOCKS5 protocol
|
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
||||||
- Supports Netfilter TCP redirecting
|
- Rules based off domains, GEOIP, IP CIDR or ports to forward packets to different nodes
|
||||||
- Comprehensive HTTP API
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node based off latency
|
||||||
|
- Remote providers, allowing users to get node lists remotely instead of hardcoding in config
|
||||||
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Install
|
## Premium Features
|
||||||
|
|
||||||
Clash Requires Go >= 1.13. You can build it from source:
|
- TUN mode on macOS, Linux and Windows. [Doc](https://github.com/Dreamacro/clash/wiki/premium-core-features#tun-device)
|
||||||
|
- Match your tunnel by [Script](https://github.com/Dreamacro/clash/wiki/premium-core-features#script)
|
||||||
|
- [Rule Provider](https://github.com/Dreamacro/clash/wiki/premium-core-features#rule-providers)
|
||||||
|
|
||||||
```sh
|
## Getting Started
|
||||||
$ go get -u -v github.com/Dreamacro/clash
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
```
|
|
||||||
|
|
||||||
Pre-built binaries are available here: [release](https://github.com/Dreamacro/clash/releases)
|
## Premium Release
|
||||||
|
[Release](https://github.com/Dreamacro/clash/releases/tag/premium)
|
||||||
|
|
||||||
Pre-built TUN mode binaries are available here: [TUN release](https://github.com/Dreamacro/clash/releases/tag/TUN)
|
## 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)
|
||||||
|
|
||||||
Check Clash version with:
|
## Credits
|
||||||
|
|
||||||
```sh
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
$ clash -v
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
```
|
|
||||||
|
|
||||||
## Daemon
|
|
||||||
|
|
||||||
Unfortunately, there is no native and elegant way to implement daemons on Golang.
|
|
||||||
|
|
||||||
So we can use third-party daemon tools like PM2, Supervisor or the like.
|
|
||||||
|
|
||||||
In the case of [pm2](https://github.com/Unitech/pm2), we can start the daemon this way:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ pm2 start clash
|
|
||||||
```
|
|
||||||
|
|
||||||
If you have Docker installed, you can run clash directly using `docker-compose`.
|
|
||||||
|
|
||||||
[Run clash in docker](https://github.com/Dreamacro/clash/wiki/Run-clash-in-docker)
|
|
||||||
|
|
||||||
## Config
|
|
||||||
|
|
||||||
The default configuration directory is `$HOME/.config/clash`.
|
|
||||||
|
|
||||||
The name of the configuration file is `config.yaml`.
|
|
||||||
|
|
||||||
If you want to use another directory, use `-d` to control the configuration directory.
|
|
||||||
|
|
||||||
For example, you can use the current directory as the configuration directory:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ clash -d .
|
|
||||||
```
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>This is an example configuration file (click to expand)</summary>
|
|
||||||
|
|
||||||
```yml
|
|
||||||
# port of HTTP
|
|
||||||
port: 7890
|
|
||||||
|
|
||||||
# port of SOCKS5
|
|
||||||
socks-port: 7891
|
|
||||||
|
|
||||||
# redir port for Linux and macOS
|
|
||||||
# redir-port: 7892
|
|
||||||
|
|
||||||
allow-lan: false
|
|
||||||
|
|
||||||
# Only applicable when setting allow-lan to true
|
|
||||||
# "*": bind all IP addresses
|
|
||||||
# 192.168.122.11: bind a single IPv4 address
|
|
||||||
# "[aaaa::a8aa:ff:fe09:57d8]": bind a single IPv6 address
|
|
||||||
# bind-address: "*"
|
|
||||||
|
|
||||||
# Rule / Global/ Direct (default is Rule)
|
|
||||||
mode: Rule
|
|
||||||
|
|
||||||
# set log level to stdout (default is info)
|
|
||||||
# info / warning / error / debug / silent
|
|
||||||
log-level: info
|
|
||||||
|
|
||||||
# RESTful API for clash
|
|
||||||
external-controller: 127.0.0.1:9090
|
|
||||||
|
|
||||||
# you can put the static web resource (such as clash-dashboard) to a directory, and clash would serve in `${API}/ui`
|
|
||||||
# input is a relative path to the configuration directory or an absolute path
|
|
||||||
# external-ui: folder
|
|
||||||
|
|
||||||
# Secret for RESTful API (Optional)
|
|
||||||
# secret: ""
|
|
||||||
|
|
||||||
# experimental feature
|
|
||||||
experimental:
|
|
||||||
ignore-resolve-fail: true # ignore dns resolve fail, default value is true
|
|
||||||
# interface-name: en0 # outbound interface name
|
|
||||||
|
|
||||||
# authentication of local SOCKS5/HTTP(S) server
|
|
||||||
# authentication:
|
|
||||||
# - "user1:pass1"
|
|
||||||
# - "user2:pass2"
|
|
||||||
|
|
||||||
# # experimental hosts, support wildcard (e.g. *.clash.dev Even *.foo.*.example.com)
|
|
||||||
# # static domain has a higher priority than wildcard domain (foo.example.com > *.example.com)
|
|
||||||
# hosts:
|
|
||||||
# '*.clash.dev': 127.0.0.1
|
|
||||||
# 'alpha.clash.dev': '::1'
|
|
||||||
|
|
||||||
# dns:
|
|
||||||
# enable: true # set true to enable dns (default is false)
|
|
||||||
# ipv6: false # default is false
|
|
||||||
# listen: 0.0.0.0:53
|
|
||||||
# # default-nameserver: # resolve dns nameserver host, should fill pure IP
|
|
||||||
# # - 114.114.114.114
|
|
||||||
# # - 8.8.8.8
|
|
||||||
# enhanced-mode: redir-host # or fake-ip
|
|
||||||
# # fake-ip-range: 198.18.0.1/16 # if you don't know what it is, don't change it
|
|
||||||
# fake-ip-filter: # fake ip white domain list
|
|
||||||
# - '*.lan'
|
|
||||||
# - localhost.ptlogin2.qq.com
|
|
||||||
# nameserver:
|
|
||||||
# - 114.114.114.114
|
|
||||||
# - tls://dns.rubyfish.cn:853 # dns over tls
|
|
||||||
# - https://1.1.1.1/dns-query # dns over https
|
|
||||||
# fallback: # concurrent request with nameserver, fallback used when GEOIP country isn't CN
|
|
||||||
# - tcp://1.1.1.1
|
|
||||||
# fallback-filter:
|
|
||||||
# geoip: true # default
|
|
||||||
# ipcidr: # ips in these subnets will be considered polluted
|
|
||||||
# - 240.0.0.0/4
|
|
||||||
|
|
||||||
Proxy:
|
|
||||||
# shadowsocks
|
|
||||||
# The supported ciphers(encrypt methods):
|
|
||||||
# aes-128-gcm aes-192-gcm aes-256-gcm
|
|
||||||
# aes-128-cfb aes-192-cfb aes-256-cfb
|
|
||||||
# aes-128-ctr aes-192-ctr aes-256-ctr
|
|
||||||
# rc4-md5 chacha20-ietf xchacha20
|
|
||||||
# chacha20-ietf-poly1305 xchacha20-ietf-poly1305
|
|
||||||
- name: "ss1"
|
|
||||||
type: ss
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
cipher: chacha20-ietf-poly1305
|
|
||||||
password: "password"
|
|
||||||
# udp: true
|
|
||||||
|
|
||||||
# old obfs configuration format remove after prerelease
|
|
||||||
- name: "ss2"
|
|
||||||
type: ss
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
cipher: chacha20-ietf-poly1305
|
|
||||||
password: "password"
|
|
||||||
plugin: obfs
|
|
||||||
plugin-opts:
|
|
||||||
mode: tls # or http
|
|
||||||
# host: bing.com
|
|
||||||
|
|
||||||
- name: "ss3"
|
|
||||||
type: ss
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
cipher: chacha20-ietf-poly1305
|
|
||||||
password: "password"
|
|
||||||
plugin: v2ray-plugin
|
|
||||||
plugin-opts:
|
|
||||||
mode: websocket # no QUIC now
|
|
||||||
# tls: true # wss
|
|
||||||
# skip-cert-verify: true
|
|
||||||
# host: bing.com
|
|
||||||
# path: "/"
|
|
||||||
# mux: true
|
|
||||||
# headers:
|
|
||||||
# custom: value
|
|
||||||
|
|
||||||
# vmess
|
|
||||||
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
|
||||||
- name: "vmess"
|
|
||||||
type: vmess
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
alterId: 32
|
|
||||||
cipher: auto
|
|
||||||
# udp: true
|
|
||||||
# tls: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
# network: ws
|
|
||||||
# ws-path: /path
|
|
||||||
# ws-headers:
|
|
||||||
# Host: v2ray.com
|
|
||||||
|
|
||||||
# socks5
|
|
||||||
- name: "socks"
|
|
||||||
type: socks5
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
# username: username
|
|
||||||
# password: password
|
|
||||||
# tls: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
# udp: true
|
|
||||||
|
|
||||||
# http
|
|
||||||
- name: "http"
|
|
||||||
type: http
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
# username: username
|
|
||||||
# password: password
|
|
||||||
# tls: true # https
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
# snell
|
|
||||||
- name: "snell"
|
|
||||||
type: snell
|
|
||||||
server: server
|
|
||||||
port: 44046
|
|
||||||
psk: yourpsk
|
|
||||||
# obfs-opts:
|
|
||||||
# mode: http # or tls
|
|
||||||
# host: bing.com
|
|
||||||
|
|
||||||
Proxy Group:
|
|
||||||
# url-test select which proxy will be used by benchmarking speed to a URL.
|
|
||||||
- name: "auto"
|
|
||||||
type: url-test
|
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- ss2
|
|
||||||
- vmess1
|
|
||||||
url: 'http://www.gstatic.com/generate_204'
|
|
||||||
interval: 300
|
|
||||||
|
|
||||||
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
|
||||||
- name: "fallback-auto"
|
|
||||||
type: fallback
|
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- ss2
|
|
||||||
- vmess1
|
|
||||||
url: 'http://www.gstatic.com/generate_204'
|
|
||||||
interval: 300
|
|
||||||
|
|
||||||
# load-balance: The request of the same eTLD will be dial on the same proxy.
|
|
||||||
- name: "load-balance"
|
|
||||||
type: load-balance
|
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- ss2
|
|
||||||
- vmess1
|
|
||||||
url: 'http://www.gstatic.com/generate_204'
|
|
||||||
interval: 300
|
|
||||||
|
|
||||||
# select is used for selecting proxy or proxy group
|
|
||||||
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
|
||||||
- name: Proxy
|
|
||||||
type: select
|
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- ss2
|
|
||||||
- vmess1
|
|
||||||
- auto
|
|
||||||
|
|
||||||
Rule:
|
|
||||||
- DOMAIN-SUFFIX,google.com,auto
|
|
||||||
- DOMAIN-KEYWORD,google,auto
|
|
||||||
- DOMAIN,google.com,auto
|
|
||||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
|
||||||
# rename SOURCE-IP-CIDR and would remove after prerelease
|
|
||||||
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
|
||||||
# optional param "no-resolve" for IP rules (GEOIP IP-CIDR)
|
|
||||||
- IP-CIDR,127.0.0.0/8,DIRECT
|
|
||||||
- GEOIP,CN,DIRECT
|
|
||||||
- DST-PORT,80,DIRECT
|
|
||||||
- SRC-PORT,7777,DIRECT
|
|
||||||
# FINAL would remove after prerelease
|
|
||||||
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
|
||||||
- MATCH,auto
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
|
|
||||||
## Advanced
|
|
||||||
[Provider](https://github.com/Dreamacro/clash/wiki/Provider)
|
|
||||||
|
|
||||||
## Documentations
|
|
||||||
https://clash.gitbook.io/
|
|
||||||
|
|
||||||
## Thanks
|
|
||||||
|
|
||||||
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
|
||||||
|
|
||||||
[v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
This software is released under the GPL-3.0 license.
|
||||||
|
|
||||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
||||||
|
|
||||||
## TODO
|
## TODO
|
||||||
@ -324,4 +60,3 @@ https://clash.gitbook.io/
|
|||||||
- [x] Redir proxy
|
- [x] Redir proxy
|
||||||
- [x] UDP support
|
- [x] UDP support
|
||||||
- [x] Connection manager
|
- [x] Connection manager
|
||||||
- [ ] Event API
|
|
||||||
|
@ -1,116 +1,48 @@
|
|||||||
package outbound
|
package adapter
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
defaultURLTestTimeout = time.Second * 5
|
|
||||||
)
|
|
||||||
|
|
||||||
type Base struct {
|
|
||||||
name string
|
|
||||||
tp C.AdapterType
|
|
||||||
udp bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) Name() string {
|
|
||||||
return b.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) Type() C.AdapterType {
|
|
||||||
return b.tp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) SupportUDP() bool {
|
|
||||||
return b.udp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]string{
|
|
||||||
"type": b.Type().String(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBase(name string, tp C.AdapterType, udp bool) *Base {
|
|
||||||
return &Base{name, tp, udp}
|
|
||||||
}
|
|
||||||
|
|
||||||
type conn struct {
|
|
||||||
net.Conn
|
|
||||||
chain C.Chain
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *conn) Chains() C.Chain {
|
|
||||||
return c.chain
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|
||||||
c.chain = append(c.chain, a.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
func newConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
|
||||||
return &conn{c, []string{a.Name()}}
|
|
||||||
}
|
|
||||||
|
|
||||||
type PacketConn interface {
|
|
||||||
net.PacketConn
|
|
||||||
WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type packetConn struct {
|
|
||||||
PacketConn
|
|
||||||
chain C.Chain
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) Chains() C.Chain {
|
|
||||||
return c.chain
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|
||||||
c.chain = append(c.chain, a.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPacketConn(pc PacketConn, a C.ProxyAdapter) C.PacketConn {
|
|
||||||
return &packetConn{pc, []string{a.Name()}}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
history *queue.Queue
|
history *queue.Queue
|
||||||
alive bool
|
alive *atomic.Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Alive implements C.Proxy
|
||||||
func (p *Proxy) Alive() bool {
|
func (p *Proxy) Alive() bool {
|
||||||
return p.alive
|
return p.alive.Load()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dial implements C.Proxy
|
||||||
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
return p.DialContext(ctx, metadata)
|
return p.DialContext(ctx, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
p.alive = false
|
p.alive.Store(false)
|
||||||
}
|
}
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DelayHistory implements C.Proxy
|
||||||
func (p *Proxy) DelayHistory() []C.DelayHistory {
|
func (p *Proxy) DelayHistory() []C.DelayHistory {
|
||||||
queue := p.history.Copy()
|
queue := p.history.Copy()
|
||||||
histories := []C.DelayHistory{}
|
histories := []C.DelayHistory{}
|
||||||
@ -121,9 +53,10 @@ func (p *Proxy) DelayHistory() []C.DelayHistory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
||||||
|
// implements C.Proxy
|
||||||
func (p *Proxy) LastDelay() (delay uint16) {
|
func (p *Proxy) LastDelay() (delay uint16) {
|
||||||
var max uint16 = 0xffff
|
var max uint16 = 0xffff
|
||||||
if !p.alive {
|
if !p.alive.Load() {
|
||||||
return max
|
return max
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -138,6 +71,7 @@ func (p *Proxy) LastDelay() (delay uint16) {
|
|||||||
return history.Delay
|
return history.Delay
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||||
inner, err := p.ProxyAdapter.MarshalJSON()
|
inner, err := p.ProxyAdapter.MarshalJSON()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -148,13 +82,15 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
json.Unmarshal(inner, &mapping)
|
json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
|
mapping["udp"] = p.SupportUDP()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
// URLTest get the delay for the specified URL
|
||||||
|
// implements C.Proxy
|
||||||
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
p.alive = err == nil
|
p.alive.Store(err == nil)
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
record.Delay = t
|
record.Delay = t
|
||||||
@ -194,7 +130,14 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{
|
||||||
|
Transport: transport,
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
},
|
||||||
|
}
|
||||||
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@ -205,5 +148,33 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
return &Proxy{adapter, queue.New(10), true}
|
return &Proxy{adapter, queue.New(10), atomic.NewBool(true)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
|
u, err := url.Parse(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
port := u.Port()
|
||||||
|
if port == "" {
|
||||||
|
switch u.Scheme {
|
||||||
|
case "https":
|
||||||
|
port = "443"
|
||||||
|
case "http":
|
||||||
|
port = "80"
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf("%s scheme not Support", rawURL)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = C.Metadata{
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: u.Hostname(),
|
||||||
|
DstIP: nil,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
21
adapter/inbound/http.go
Normal file
21
adapter/inbound/http.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
|
func NewHTTP(target string, source net.Addr, conn net.Conn) *context.ConnContext {
|
||||||
|
metadata := parseSocksAddr(socks5.ParseAddr(target))
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = C.HTTP
|
||||||
|
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
@ -5,18 +5,16 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS is HTTPAdapter generator
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPCONNECT
|
metadata.Type = C.HTTPCONNECT
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
return &SocketAdapter{
|
return context.NewConnContext(conn, metadata)
|
||||||
metadata: metadata,
|
|
||||||
Conn: conn,
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -1,8 +1,8 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
22
adapter/inbound/socket.go
Normal file
22
adapter/inbound/socket.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = source
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
@ -4,9 +4,10 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
@ -16,7 +17,8 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
metadata.Host = string(target[2 : 2+target[1]])
|
// trim for FQDN
|
||||||
|
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
||||||
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
case socks5.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
ip := net.IP(target[1 : 1+net.IPv4len])
|
ip := net.IP(target[1 : 1+net.IPv4len])
|
||||||
@ -38,6 +40,9 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
port = "80"
|
port = "80"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trim FQDN (#737)
|
||||||
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
AddrType: C.AtypDomainName,
|
AddrType: C.AtypDomainName,
|
100
adapter/outbound/base.go
Normal file
100
adapter/outbound/base.go
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Base struct {
|
||||||
|
name string
|
||||||
|
addr string
|
||||||
|
tp C.AdapterType
|
||||||
|
udp bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name implements C.ProxyAdapter
|
||||||
|
func (b *Base) Name() string {
|
||||||
|
return b.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type implements C.ProxyAdapter
|
||||||
|
func (b *Base) Type() C.AdapterType {
|
||||||
|
return b.tp
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
return c, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (b *Base) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (b *Base) SupportUDP() bool {
|
||||||
|
return b.udp
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": b.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Addr implements C.ProxyAdapter
|
||||||
|
func (b *Base) Addr() string {
|
||||||
|
return b.addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBase(name string, addr string, tp C.AdapterType, udp bool) *Base {
|
||||||
|
return &Base{name, addr, tp, udp}
|
||||||
|
}
|
||||||
|
|
||||||
|
type conn struct {
|
||||||
|
net.Conn
|
||||||
|
chain C.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chains implements C.Connection
|
||||||
|
func (c *conn) Chains() C.Chain {
|
||||||
|
return c.chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendToChains implements C.Connection
|
||||||
|
func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
||||||
|
c.chain = append(c.chain, a.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
|
return &conn{c, []string{a.Name()}}
|
||||||
|
}
|
||||||
|
|
||||||
|
type packetConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
chain C.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chains implements C.Connection
|
||||||
|
func (c *packetConn) Chains() C.Chain {
|
||||||
|
return c.chain
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendToChains implements C.Connection
|
||||||
|
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
||||||
|
c.chain = append(c.chain, a.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
|
return &packetConn{pc, []string{a.Name()}}
|
||||||
|
}
|
@ -5,7 +5,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -13,22 +12,19 @@ type Direct struct {
|
|||||||
*Base
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
address := net.JoinHostPort(metadata.Host, metadata.DstPort)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
if metadata.DstIP != nil {
|
|
||||||
address = net.JoinHostPort(metadata.DstIP.String(), metadata.DstPort)
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", address)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return newConn(c, d), nil
|
return NewConn(c, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
func (d *Direct) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
func (d *Direct) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := dialer.ListenPacket("udp", "")
|
pc, err := dialer.ListenPacket(context.Background(), "udp", "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -39,17 +35,6 @@ type directPacketConn struct {
|
|||||||
net.PacketConn
|
net.PacketConn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (dp *directPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
return dp.WriteTo(p, metadata.UDPAddr())
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
@ -19,7 +19,6 @@ import (
|
|||||||
|
|
||||||
type Http struct {
|
type Http struct {
|
||||||
*Base
|
*Base
|
||||||
addr string
|
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
@ -32,26 +31,43 @@ type HttpOption struct {
|
|||||||
UserName string `proxy:"username,omitempty"`
|
UserName string `proxy:"username,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
// StreamConn implements C.ProxyAdapter
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if err == nil && h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
err = cc.Handshake()
|
err := cc.Handshake()
|
||||||
c = cc
|
c = cc
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := h.shakeHand(metadata, c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
if err := h.shakeHand(metadata, c); err != nil {
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = h.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return newConn(c, h), nil
|
return NewConn(c, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
@ -103,19 +119,22 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
func NewHttp(option HttpOption) *Http {
|
func NewHttp(option HttpOption) *Http {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
|
sni := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
sni = option.SNI
|
||||||
|
}
|
||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ClientSessionCache: getClientSessionCache(),
|
ServerName: sni,
|
||||||
ServerName: option.Server,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Http{
|
return &Http{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
},
|
},
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
@ -14,10 +14,12 @@ type Reject struct {
|
|||||||
*Base
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return newConn(&NopConn{}, r), nil
|
return NewConn(&NopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
func (r *Reject) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
func (r *Reject) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
return nil, errors.New("match reject rule")
|
return nil, errors.New("match reject rule")
|
||||||
}
|
}
|
@ -2,25 +2,23 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"errors"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
v2rayObfs "github.com/Dreamacro/clash/component/v2ray-plugin"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
server string
|
|
||||||
cipher core.Cipher
|
cipher core.Cipher
|
||||||
|
|
||||||
// obfs
|
// obfs
|
||||||
@ -38,14 +36,10 @@ type ShadowSocksOption struct {
|
|||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
||||||
|
|
||||||
// deprecated when bump to 1.0
|
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
|
||||||
ObfsHost string `proxy:"obfs-host,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
Mode string `obfs:"mode"`
|
Mode string `obfs:"mode,omitempty"`
|
||||||
Host string `obfs:"host,omitempty"`
|
Host string `obfs:"host,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,38 +53,50 @@ type v2rayObfsOption struct {
|
|||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
// StreamConn implements C.ProxyAdapter
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.server)
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.server, err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
case "http":
|
case "http":
|
||||||
_, port, _ := net.SplitHostPort(ss.server)
|
_, port, _ := net.SplitHostPort(ss.addr)
|
||||||
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||||
case "websocket":
|
case "websocket":
|
||||||
var err error
|
var err error
|
||||||
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.server, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c = ss.cipher.StreamConn(c)
|
c = ss.cipher.StreamConn(c)
|
||||||
_, err = c.Write(serializesSocksAddr(metadata))
|
_, err := c.Write(serializesSocksAddr(metadata))
|
||||||
return newConn(c, ss), err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = ss.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, ss), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := dialer.ListenPacket("udp", "")
|
pc, err := dialer.ListenPacket(context.Background(), "udp", "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ss.server)
|
addr, err := resolveUDPAddr("udp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,83 +104,61 @@ func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]string{
|
|
||||||
"type": ss.Type().String(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
server := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
cipher := option.Cipher
|
cipher := option.Cipher
|
||||||
password := option.Password
|
password := option.Password
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
ciph, err := core.PickCipher(cipher, nil, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", server, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
// forward compatibility before 1.0
|
|
||||||
if option.Obfs != "" {
|
|
||||||
obfsMode = option.Obfs
|
|
||||||
obfsOption = &simpleObfsOption{
|
|
||||||
Host: "bing.com",
|
|
||||||
}
|
|
||||||
if option.ObfsHost != "" {
|
|
||||||
obfsOption.Host = option.ObfsHost
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
if option.Plugin == "obfs" {
|
if option.Plugin == "obfs" {
|
||||||
opts := simpleObfsOption{Host: "bing.com"}
|
opts := simpleObfsOption{Host: "bing.com"}
|
||||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize obfs error: %w", server, err)
|
return nil, fmt.Errorf("ss %s initialize obfs error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.Mode != "tls" && opts.Mode != "http" {
|
if opts.Mode != "tls" && opts.Mode != "http" {
|
||||||
return nil, fmt.Errorf("ss %s obfs mode error: %s", server, opts.Mode)
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
}
|
}
|
||||||
obfsMode = opts.Mode
|
obfsMode = opts.Mode
|
||||||
obfsOption = &opts
|
obfsOption = &opts
|
||||||
} else if option.Plugin == "v2ray-plugin" {
|
} else if option.Plugin == "v2ray-plugin" {
|
||||||
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
|
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
|
||||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", server, err)
|
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.Mode != "websocket" {
|
if opts.Mode != "websocket" {
|
||||||
return nil, fmt.Errorf("ss %s obfs mode error: %s", server, opts.Mode)
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
}
|
}
|
||||||
obfsMode = opts.Mode
|
obfsMode = opts.Mode
|
||||||
|
|
||||||
var tlsConfig *tls.Config
|
|
||||||
if opts.TLS {
|
|
||||||
tlsConfig = &tls.Config{
|
|
||||||
ServerName: opts.Host,
|
|
||||||
InsecureSkipVerify: opts.SkipCertVerify,
|
|
||||||
ClientSessionCache: getClientSessionCache(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
v2rayOption = &v2rayObfs.Option{
|
v2rayOption = &v2rayObfs.Option{
|
||||||
Host: opts.Host,
|
Host: opts.Host,
|
||||||
Path: opts.Path,
|
Path: opts.Path,
|
||||||
Headers: opts.Headers,
|
Headers: opts.Headers,
|
||||||
TLSConfig: tlsConfig,
|
Mux: opts.Mux,
|
||||||
Mux: opts.Mux,
|
}
|
||||||
|
|
||||||
|
if opts.TLS {
|
||||||
|
v2rayOption.TLS = true
|
||||||
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
},
|
},
|
||||||
server: server,
|
|
||||||
cipher: ciph,
|
cipher: ciph,
|
||||||
|
|
||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
@ -196,20 +180,22 @@ func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
|||||||
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (spc *ssPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
|
||||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddr(metadata.RemoteAddress()), p)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
n, _, e := spc.PacketConn.ReadFrom(b)
|
n, _, e := spc.PacketConn.ReadFrom(b)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return 0, nil, e
|
return 0, nil, e
|
||||||
}
|
}
|
||||||
|
|
||||||
addr := socks5.SplitAddr(b[:n])
|
addr := socks5.SplitAddr(b[:n])
|
||||||
|
if addr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
copy(b, b[len(addr):])
|
copy(b, b[len(addr):])
|
||||||
return n - len(addr), addr.UDPAddr(), e
|
return n - len(addr), udpAddr, e
|
||||||
}
|
}
|
148
adapter/outbound/shadowsocksr.go
Normal file
148
adapter/outbound/shadowsocksr.go
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowstream"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ShadowSocksR struct {
|
||||||
|
*Base
|
||||||
|
cipher core.Cipher
|
||||||
|
obfs obfs.Obfs
|
||||||
|
protocol protocol.Protocol
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShadowSocksROption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
Obfs string `proxy:"obfs"`
|
||||||
|
ObfsParam string `proxy:"obfs-param,omitempty"`
|
||||||
|
Protocol string `proxy:"protocol"`
|
||||||
|
ProtocolParam string `proxy:"protocol-param,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
c = ssr.obfs.StreamConn(c)
|
||||||
|
c = ssr.cipher.StreamConn(c)
|
||||||
|
var (
|
||||||
|
iv []byte
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
switch conn := c.(type) {
|
||||||
|
case *shadowstream.Conn:
|
||||||
|
iv, err = conn.ObtainWriteIV()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case *shadowaead.Conn:
|
||||||
|
return nil, fmt.Errorf("invalid connection type")
|
||||||
|
}
|
||||||
|
c = ssr.protocol.StreamConn(c, iv)
|
||||||
|
_, err = c.Write(serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, ssr), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := dialer.ListenPacket(context.Background(), "udp", "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ssr.addr)
|
||||||
|
if err != nil {
|
||||||
|
pc.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc = ssr.cipher.PacketConn(pc)
|
||||||
|
pc = ssr.protocol.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
cipher := option.Cipher
|
||||||
|
password := option.Password
|
||||||
|
coreCiph, err := core.PickCipher(cipher, nil, password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ssr %s initialize error: %w", addr, err)
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
ivSize int
|
||||||
|
key []byte
|
||||||
|
)
|
||||||
|
if option.Cipher == "dummy" {
|
||||||
|
ivSize = 0
|
||||||
|
key = core.Kdf(option.Password, 16)
|
||||||
|
} else {
|
||||||
|
ciph, ok := coreCiph.(*core.StreamCipher)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("%s is not dummy or a supported stream cipher in ssr", cipher)
|
||||||
|
}
|
||||||
|
ivSize = ciph.IVSize()
|
||||||
|
key = ciph.Key
|
||||||
|
}
|
||||||
|
|
||||||
|
obfs, obfsOverhead, err := obfs.PickObfs(option.Obfs, &obfs.Base{
|
||||||
|
Host: option.Server,
|
||||||
|
Port: option.Port,
|
||||||
|
Key: key,
|
||||||
|
IVSize: ivSize,
|
||||||
|
Param: option.ObfsParam,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ssr %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
protocol, err := protocol.PickProtocol(option.Protocol, &protocol.Base{
|
||||||
|
Key: key,
|
||||||
|
Overhead: obfsOverhead,
|
||||||
|
Param: option.ProtocolParam,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ssr %s initialize protocol error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ShadowSocksR{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.ShadowsocksR,
|
||||||
|
udp: option.UDP,
|
||||||
|
},
|
||||||
|
cipher: coreCiph,
|
||||||
|
obfs: obfs,
|
||||||
|
protocol: protocol,
|
||||||
|
}, nil
|
||||||
|
}
|
135
adapter/outbound/snell.go
Normal file
135
adapter/outbound/snell.go
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/snell"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Snell struct {
|
||||||
|
*Base
|
||||||
|
psk []byte
|
||||||
|
pool *snell.Pool
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
version int
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnellOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Psk string `proxy:"psk"`
|
||||||
|
Version int `proxy:"version,omitempty"`
|
||||||
|
ObfsOpts map[string]interface{} `proxy:"obfs-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type streamOption struct {
|
||||||
|
psk []byte
|
||||||
|
version int
|
||||||
|
addr string
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
}
|
||||||
|
|
||||||
|
func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
||||||
|
switch option.obfsOption.Mode {
|
||||||
|
case "tls":
|
||||||
|
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
|
||||||
|
case "http":
|
||||||
|
_, port, _ := net.SplitHostPort(option.addr)
|
||||||
|
c = obfs.NewHTTPObfs(c, option.obfsOption.Host, port)
|
||||||
|
}
|
||||||
|
return snell.StreamConn(c, option.psk, option.version)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if s.version == snell.Version2 {
|
||||||
|
c, err := s.pool.Get()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = s.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
psk := []byte(option.Psk)
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
|
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
||||||
|
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
||||||
|
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch obfsOption.Mode {
|
||||||
|
case "tls", "http", "":
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// backward compatible
|
||||||
|
if option.Version == 0 {
|
||||||
|
option.Version = snell.DefaultSnellVersion
|
||||||
|
}
|
||||||
|
if option.Version != snell.Version1 && option.Version != snell.Version2 {
|
||||||
|
return nil, fmt.Errorf("snell version error: %d", option.Version)
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Snell{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Snell,
|
||||||
|
},
|
||||||
|
psk: psk,
|
||||||
|
obfsOption: obfsOption,
|
||||||
|
version: option.Version,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Version == snell.Version2 {
|
||||||
|
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
@ -3,6 +3,7 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
@ -10,13 +11,12 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
*Base
|
*Base
|
||||||
addr string
|
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
@ -35,19 +35,17 @@ type Socks5Option struct {
|
|||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
// StreamConn implements C.ProxyAdapter
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
if ss.tls {
|
||||||
if err == nil && ss.tls {
|
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err = cc.Handshake()
|
err := cc.Handshake()
|
||||||
c = cc
|
c = cc
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
if ss.user != "" {
|
if ss.user != "" {
|
||||||
user = &socks5.User{
|
user = &socks5.User{
|
||||||
@ -58,11 +56,30 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn
|
|||||||
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newConn(c, ss), nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = ss.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -76,11 +93,7 @@ func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|||||||
c = cc
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer safeConnClose(c, err)
|
||||||
if err != nil {
|
|
||||||
c.Close()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
@ -97,7 +110,7 @@ func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket("udp", "")
|
pc, err := dialer.ListenPacket(context.Background(), "udp", "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -110,7 +123,21 @@ func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|||||||
pc.Close()
|
pc.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindAddr.UDPAddr(), tcpConn: c}, ss), nil
|
// Support unspecified UDP bind address.
|
||||||
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
@ -118,7 +145,6 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
|||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ClientSessionCache: getClientSessionCache(),
|
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -126,10 +152,10 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
|||||||
return &Socks5{
|
return &Socks5{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
},
|
},
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
@ -152,16 +178,8 @@ func (uc *socksPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
|||||||
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *socksPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
|
||||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddr(metadata.RemoteAddress()), p)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
n, a, e := uc.PacketConn.ReadFrom(b)
|
n, _, e := uc.PacketConn.ReadFrom(b)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return 0, nil, e
|
return 0, nil, e
|
||||||
}
|
}
|
||||||
@ -169,10 +187,15 @@ func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, nil, err
|
return 0, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse udp addr error")
|
||||||
|
}
|
||||||
|
|
||||||
// due to DecodeUDPPacket is mutable, record addr length
|
// due to DecodeUDPPacket is mutable, record addr length
|
||||||
addrLength := len(addr)
|
|
||||||
copy(b, payload)
|
copy(b, payload)
|
||||||
return n - addrLength - 3, a, nil
|
return n - len(addr) - 3, udpAddr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *socksPacketConn) Close() error {
|
func (uc *socksPacketConn) Close() error {
|
176
adapter/outbound/trojan.go
Normal file
176
adapter/outbound/trojan.go
Normal file
@ -0,0 +1,176 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Trojan struct {
|
||||||
|
*Base
|
||||||
|
instance *trojan.Trojan
|
||||||
|
|
||||||
|
// for gun mux
|
||||||
|
gunTLSConfig *tls.Config
|
||||||
|
gunConfig *gun.Config
|
||||||
|
transport *http2.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
type TrojanOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Network string `proxy:"network,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
if t.transport != nil {
|
||||||
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = t.instance.StreamConn(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
// gun transport
|
||||||
|
if t.transport != nil {
|
||||||
|
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = t.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
var c net.Conn
|
||||||
|
|
||||||
|
// grpc transport
|
||||||
|
if t.transport != nil {
|
||||||
|
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
} else {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||||
|
defer cancel()
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = t.instance.StreamConn(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
|
tOption := &trojan.Option{
|
||||||
|
Password: option.Password,
|
||||||
|
ALPN: option.ALPN,
|
||||||
|
ServerName: option.Server,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.SNI != "" {
|
||||||
|
tOption.ServerName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
t := &Trojan{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Trojan,
|
||||||
|
udp: option.UDP,
|
||||||
|
},
|
||||||
|
instance: trojan.New(tOption),
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Network == "grpc" {
|
||||||
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(context.Background(), "tcp", t.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
NextProtos: option.ALPN,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
InsecureSkipVerify: tOption.SkipCertVerify,
|
||||||
|
ServerName: tOption.ServerName,
|
||||||
|
}
|
||||||
|
|
||||||
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
t.gunTLSConfig = tlsConfig
|
||||||
|
t.gunConfig = &gun.Config{
|
||||||
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
|
Host: tOption.ServerName,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
@ -2,56 +2,15 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/tls"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
tcpTimeout = 5 * time.Second
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
globalClientSessionCache tls.ClientSessionCache
|
|
||||||
once sync.Once
|
|
||||||
)
|
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|
||||||
u, err := url.Parse(rawURL)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
port := u.Port()
|
|
||||||
if port == "" {
|
|
||||||
switch u.Scheme {
|
|
||||||
case "https":
|
|
||||||
port = "443"
|
|
||||||
case "http":
|
|
||||||
port = "80"
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf("%s scheme not Support", rawURL)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
addr = C.Metadata{
|
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: u.Hostname(),
|
|
||||||
DstIP: nil,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
tcp.SetKeepAlive(true)
|
tcp.SetKeepAlive(true)
|
||||||
@ -59,13 +18,6 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getClientSessionCache() tls.ClientSessionCache {
|
|
||||||
once.Do(func() {
|
|
||||||
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
|
||||||
})
|
|
||||||
return globalClientSessionCache
|
|
||||||
}
|
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
aType := uint8(metadata.AddrType)
|
aType := uint8(metadata.AddrType)
|
||||||
@ -98,3 +50,9 @@ func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|||||||
}
|
}
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func safeConnClose(c net.Conn, err error) {
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
}
|
367
adapter/outbound/vmess.go
Normal file
367
adapter/outbound/vmess.go
Normal file
@ -0,0 +1,367 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Vmess struct {
|
||||||
|
*Base
|
||||||
|
client *vmess.Client
|
||||||
|
option *VmessOption
|
||||||
|
|
||||||
|
// for gun mux
|
||||||
|
gunTLSConfig *tls.Config
|
||||||
|
gunConfig *gun.Config
|
||||||
|
transport *http2.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
type VmessOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UUID string `proxy:"uuid"`
|
||||||
|
AlterID int `proxy:"alterId"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Network string `proxy:"network,omitempty"`
|
||||||
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPOptions struct {
|
||||||
|
Method string `proxy:"method,omitempty"`
|
||||||
|
Path []string `proxy:"path,omitempty"`
|
||||||
|
Headers map[string][]string `proxy:"headers,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTP2Options struct {
|
||||||
|
Host []string `proxy:"host,omitempty"`
|
||||||
|
Path string `proxy:"path,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GrpcOptions struct {
|
||||||
|
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type WSOptions struct {
|
||||||
|
Path string `proxy:"path,omitempty"`
|
||||||
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
|
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
||||||
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
switch v.option.Network {
|
||||||
|
case "ws":
|
||||||
|
if v.option.WSOpts.Path == "" {
|
||||||
|
v.option.WSOpts.Path = v.option.WSPath
|
||||||
|
}
|
||||||
|
if len(v.option.WSOpts.Headers) == 0 {
|
||||||
|
v.option.WSOpts.Headers = v.option.WSHeaders
|
||||||
|
}
|
||||||
|
|
||||||
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
|
Host: host,
|
||||||
|
Port: port,
|
||||||
|
Path: v.option.WSOpts.Path,
|
||||||
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
|
for key, value := range v.option.WSHeaders {
|
||||||
|
header.Add(key, value)
|
||||||
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.TLS {
|
||||||
|
wsOpts.TLS = true
|
||||||
|
wsOpts.SkipCertVerify = v.option.SkipCertVerify
|
||||||
|
wsOpts.ServerName = v.option.ServerName
|
||||||
|
}
|
||||||
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
|
case "http":
|
||||||
|
// readability first, so just copy default TLS logic
|
||||||
|
if v.option.TLS {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsOpts := &vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
httpOpts := &vmess.HTTPConfig{
|
||||||
|
Host: host,
|
||||||
|
Method: v.option.HTTPOpts.Method,
|
||||||
|
Path: v.option.HTTPOpts.Path,
|
||||||
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
|
}
|
||||||
|
|
||||||
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
|
case "h2":
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsOpts := vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
NextProtos: []string{"h2"},
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, &tlsOpts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
h2Opts := &vmess.H2Config{
|
||||||
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
|
Path: v.option.HTTP2Opts.Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamH2Conn(c, h2Opts)
|
||||||
|
case "grpc":
|
||||||
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
default:
|
||||||
|
// handle TLS
|
||||||
|
if v.option.TLS {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsOpts := &vmess.TLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
tlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil {
|
||||||
|
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, v), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
var c net.Conn
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil {
|
||||||
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
} else {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||||
|
defer cancel()
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
|
security := strings.ToLower(option.Cipher)
|
||||||
|
client, err := vmess.NewClient(vmess.Config{
|
||||||
|
UUID: option.UUID,
|
||||||
|
AlterID: uint16(option.AlterID),
|
||||||
|
Security: security,
|
||||||
|
HostName: option.Server,
|
||||||
|
Port: strconv.Itoa(option.Port),
|
||||||
|
IsAead: option.AlterID == 0,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "h2", "grpc":
|
||||||
|
if !option.TLS {
|
||||||
|
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
v := &Vmess{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Vmess,
|
||||||
|
udp: option.UDP,
|
||||||
|
},
|
||||||
|
client: client,
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "h2":
|
||||||
|
if len(option.HTTP2Opts.Host) == 0 {
|
||||||
|
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
||||||
|
}
|
||||||
|
case "grpc":
|
||||||
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(context.Background(), "tcp", v.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
gunConfig := &gun.Config{
|
||||||
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
|
Host: v.option.ServerName,
|
||||||
|
}
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
ServerName: v.option.ServerName,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
gunConfig.Host = host
|
||||||
|
}
|
||||||
|
|
||||||
|
v.gunTLSConfig = tlsConfig
|
||||||
|
v.gunConfig = gunConfig
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||||
|
var addrType byte
|
||||||
|
var addr []byte
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case C.AtypIPv4:
|
||||||
|
addrType = byte(vmess.AtypIPv4)
|
||||||
|
addr = make([]byte, net.IPv4len)
|
||||||
|
copy(addr[:], metadata.DstIP.To4())
|
||||||
|
case C.AtypIPv6:
|
||||||
|
addrType = byte(vmess.AtypIPv6)
|
||||||
|
addr = make([]byte, net.IPv6len)
|
||||||
|
copy(addr[:], metadata.DstIP.To16())
|
||||||
|
case C.AtypDomainName:
|
||||||
|
addrType = byte(vmess.AtypDomainName)
|
||||||
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
|
addr[0] = byte(len(metadata.Host))
|
||||||
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
return &vmess.DstAddr{
|
||||||
|
UDP: metadata.NetWork == C.UDP,
|
||||||
|
AddrType: addrType,
|
||||||
|
Addr: addr,
|
||||||
|
Port: uint(port),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type vmessPacketConn struct {
|
||||||
|
net.Conn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
return uc.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, err := uc.Conn.Read(b)
|
||||||
|
return n, uc.rAddr, err
|
||||||
|
}
|
24
adapter/outboundgroup/common.go
Normal file
24
adapter/outboundgroup/common.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultGetProxiesDuration = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for _, provider := range providers {
|
||||||
|
if touch {
|
||||||
|
proxies = append(proxies, provider.ProxiesWithTouch()...)
|
||||||
|
} else {
|
||||||
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
100
adapter/outboundgroup/fallback.go
Normal file
100
adapter/outboundgroup/fallback.go
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Fallback struct {
|
||||||
|
*outbound.Base
|
||||||
|
disableUDP bool
|
||||||
|
single *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Now() string {
|
||||||
|
proxy := f.findAliveProxy(false)
|
||||||
|
return proxy.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
proxy := f.findAliveProxy(true)
|
||||||
|
c, err := proxy.DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
proxy := f.findAliveProxy(true)
|
||||||
|
pc, err := proxy.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) SupportUDP() bool {
|
||||||
|
if f.disableUDP {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy := f.findAliveProxy(false)
|
||||||
|
return proxy.SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range f.proxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": f.Type().String(),
|
||||||
|
"now": f.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
proxy := f.findAliveProxy(true)
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := f.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(f.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||||
|
proxies := f.proxies(touch)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFallback(options *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
|
return &Fallback{
|
||||||
|
Base: outbound.NewBase(options.Name, "", C.Fallback, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
disableUDP: options.DisableUDP,
|
||||||
|
}
|
||||||
|
}
|
179
adapter/outboundgroup/loadbalance.go
Normal file
179
adapter/outboundgroup/loadbalance.go
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
)
|
||||||
|
|
||||||
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
||||||
|
|
||||||
|
type LoadBalance struct {
|
||||||
|
*outbound.Base
|
||||||
|
disableUDP bool
|
||||||
|
single *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
strategyFn strategyFn
|
||||||
|
}
|
||||||
|
|
||||||
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
|
func parseStrategy(config map[string]interface{}) string {
|
||||||
|
if elm, ok := config["strategy"]; ok {
|
||||||
|
if strategy, ok := elm.(string); ok {
|
||||||
|
return strategy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "consistent-hashing"
|
||||||
|
}
|
||||||
|
|
||||||
|
func getKey(metadata *C.Metadata) string {
|
||||||
|
if metadata.Host != "" {
|
||||||
|
// ip host
|
||||||
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
|
return metadata.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
|
||||||
|
return etld
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if metadata.DstIP == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata.DstIP.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func jumpHash(key uint64, buckets int32) int32 {
|
||||||
|
var b, j int64
|
||||||
|
|
||||||
|
for j < int64(buckets) {
|
||||||
|
b = j
|
||||||
|
key = key*2862933555777941757 + 1
|
||||||
|
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return int32(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
|
||||||
|
c, err = proxy.DialContext(ctx, metadata)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (pc C.PacketConn, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
|
||||||
|
return proxy.DialUDP(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) SupportUDP() bool {
|
||||||
|
return !lb.disableUDP
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyRoundRobin() strategyFn {
|
||||||
|
idx := 0
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
|
length := len(proxies)
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
idx = (idx + 1) % length
|
||||||
|
proxy := proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyConsistentHashing() strategyFn {
|
||||||
|
maxRetry := 5
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
|
buckets := int32(len(proxies))
|
||||||
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
|
idx := jumpHash(key, buckets)
|
||||||
|
proxy := proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
proxies := lb.proxies(true)
|
||||||
|
return lb.strategyFn(proxies, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := lb.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(lb.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range lb.proxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": lb.Type().String(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoadBalance(options *GroupCommonOption, providers []provider.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||||
|
var strategyFn strategyFn
|
||||||
|
switch strategy {
|
||||||
|
case "consistent-hashing":
|
||||||
|
strategyFn = strategyConsistentHashing()
|
||||||
|
case "round-robin":
|
||||||
|
strategyFn = strategyRoundRobin()
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
|
}
|
||||||
|
return &LoadBalance{
|
||||||
|
Base: outbound.NewBase(options.Name, "", C.LoadBalance, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
strategyFn: strategyFn,
|
||||||
|
disableUDP: options.DisableUDP,
|
||||||
|
}, nil
|
||||||
|
}
|
@ -4,33 +4,37 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errFormat = errors.New("format error")
|
errFormat = errors.New("format error")
|
||||||
errType = errors.New("unsupport type")
|
errType = errors.New("unsupport type")
|
||||||
errMissUse = errors.New("`use` field should not be empty")
|
|
||||||
errMissProxy = errors.New("`use` or `proxies` missing")
|
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||||
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
||||||
errDuplicateProvider = errors.New("`duplicate provider name")
|
errDuplicateProvider = errors.New("`duplicate provider name")
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupCommonOption struct {
|
type GroupCommonOption struct {
|
||||||
Name string `group:"name"`
|
Name string `group:"name"`
|
||||||
Type string `group:"type"`
|
Type string `group:"type"`
|
||||||
Proxies []string `group:"proxies,omitempty"`
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
Use []string `group:"use,omitempty"`
|
Use []string `group:"use,omitempty"`
|
||||||
URL string `group:"url,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy, providersMap map[string]provider.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
groupOption := &GroupCommonOption{}
|
groupOption := &GroupCommonOption{
|
||||||
|
Lazy: true,
|
||||||
|
}
|
||||||
if err := decoder.Decode(config, groupOption); err != nil {
|
if err := decoder.Decode(config, groupOption); err != nil {
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
@ -41,7 +45,7 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
|
|
||||||
groupName := groupOption.Name
|
groupName := groupOption.Name
|
||||||
|
|
||||||
providers := []provider.ProxyProvider{}
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
return nil, errMissProxy
|
return nil, errMissProxy
|
||||||
@ -55,7 +59,7 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
|
|
||||||
// if Use not empty, drop health check options
|
// if Use not empty, drop health check options
|
||||||
if len(groupOption.Use) != 0 {
|
if len(groupOption.Use) != 0 {
|
||||||
hc := provider.NewHealthCheck(ps, "", 0)
|
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -63,9 +67,13 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
|
|
||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
} else {
|
} else {
|
||||||
|
if _, ok := providersMap[groupName]; ok {
|
||||||
|
return nil, errDuplicateProvider
|
||||||
|
}
|
||||||
|
|
||||||
// select don't need health check
|
// select don't need health check
|
||||||
if groupOption.Type == "select" {
|
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
||||||
hc := provider.NewHealthCheck(ps, "", 0)
|
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -78,7 +86,7 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
return nil, errMissHealthCheck
|
return nil, errMissHealthCheck
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval))
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -101,13 +109,17 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
switch groupOption.Type {
|
switch groupOption.Type {
|
||||||
case "url-test":
|
case "url-test":
|
||||||
group = NewURLTest(groupName, providers)
|
opts := parseURLTestOption(config)
|
||||||
|
group = NewURLTest(groupOption, providers, opts...)
|
||||||
case "select":
|
case "select":
|
||||||
group = NewSelector(groupName, providers)
|
group = NewSelector(groupOption, providers)
|
||||||
case "fallback":
|
case "fallback":
|
||||||
group = NewFallback(groupName, providers)
|
group = NewFallback(groupOption, providers)
|
||||||
case "load-balance":
|
case "load-balance":
|
||||||
group = NewLoadBalance(groupName, providers)
|
strategy := parseStrategy(config)
|
||||||
|
return NewLoadBalance(groupOption, providers, strategy)
|
||||||
|
case "relay":
|
||||||
|
group = NewRelay(groupOption, providers)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
||||||
}
|
}
|
||||||
@ -127,15 +139,15 @@ func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProviders(mapping map[string]provider.ProxyProvider, list []string) ([]provider.ProxyProvider, error) {
|
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
||||||
var ps []provider.ProxyProvider
|
var ps []types.ProxyProvider
|
||||||
for _, name := range list {
|
for _, name := range list {
|
||||||
p, ok := mapping[name]
|
p, ok := mapping[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("'%s' not found", name)
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if p.VehicleType() == provider.Compatible {
|
if p.VehicleType() == types.Compatible {
|
||||||
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
}
|
}
|
||||||
ps = append(ps, p)
|
ps = append(ps, p)
|
109
adapter/outboundgroup/relay.go
Normal file
109
adapter/outboundgroup/relay.go
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Relay struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
var proxies []C.Proxy
|
||||||
|
for _, proxy := range r.proxies(metadata, true) {
|
||||||
|
if proxy.Type() != C.Direct {
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch len(proxies) {
|
||||||
|
case 0:
|
||||||
|
return outbound.NewDirect().DialContext(ctx, metadata)
|
||||||
|
case 1:
|
||||||
|
return proxies[0].DialContext(ctx, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
first := proxies[0]
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = last.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return outbound.NewConn(c, r), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range r.rawProxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": r.Type().String(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := r.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(r.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
|
||||||
|
proxies := r.rawProxies(touch)
|
||||||
|
|
||||||
|
for n, proxy := range proxies {
|
||||||
|
subproxy := proxy.Unwrap(metadata)
|
||||||
|
for subproxy != nil {
|
||||||
|
proxies[n] = subproxy
|
||||||
|
subproxy = subproxy.Unwrap(metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRelay(options *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
|
return &Relay{
|
||||||
|
Base: outbound.NewBase(options.Name, "", C.Relay, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
108
adapter/outboundgroup/selector.go
Normal file
108
adapter/outboundgroup/selector.go
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Selector struct {
|
||||||
|
*outbound.Base
|
||||||
|
disableUDP bool
|
||||||
|
single *singledo.Single
|
||||||
|
selected string
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := s.selectedProxy(true).DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := s.selectedProxy(true).DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (s *Selector) SupportUDP() bool {
|
||||||
|
if s.disableUDP {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.selectedProxy(false).SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": s.Type().String(),
|
||||||
|
"now": s.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Now() string {
|
||||||
|
return s.selectedProxy(false).Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Set(name string) error {
|
||||||
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
s.selected = name
|
||||||
|
s.single.Reset()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.New("proxy not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
return s.selectedProxy(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
|
elm, _, _ := s.single.Do(func() (interface{}, error) {
|
||||||
|
proxies := getProvidersProxies(s.providers, touch)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Name() == s.selected {
|
||||||
|
return proxy, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0], nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.(C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSelector(options *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
||||||
|
selected := providers[0].Proxies()[0].Name()
|
||||||
|
return &Selector{
|
||||||
|
Base: outbound.NewBase(options.Name, "", C.Selector, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
selected: selected,
|
||||||
|
disableUDP: options.DisableUDP,
|
||||||
|
}
|
||||||
|
}
|
150
adapter/outboundgroup/urltest.go
Normal file
150
adapter/outboundgroup/urltest.go
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type urlTestOption func(*URLTest)
|
||||||
|
|
||||||
|
func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
||||||
|
return func(u *URLTest) {
|
||||||
|
u.tolerance = tolerance
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type URLTest struct {
|
||||||
|
*outbound.Base
|
||||||
|
tolerance uint16
|
||||||
|
disableUDP bool
|
||||||
|
fastNode C.Proxy
|
||||||
|
single *singledo.Single
|
||||||
|
fastSingle *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Now() string {
|
||||||
|
return u.fast(false).Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
|
c, err = u.fast(true).DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialUDP implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := u.fast(true).DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
|
return u.fast(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := u.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(u.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
|
elm, _, _ := u.fastSingle.Do(func() (interface{}, error) {
|
||||||
|
proxies := u.proxies(touch)
|
||||||
|
fast := proxies[0]
|
||||||
|
min := fast.LastDelay()
|
||||||
|
fastNotExist := true
|
||||||
|
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
if u.fastNode != nil && proxy.Name() == u.fastNode.Name() {
|
||||||
|
fastNotExist = false
|
||||||
|
}
|
||||||
|
|
||||||
|
if !proxy.Alive() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delay := proxy.LastDelay()
|
||||||
|
if delay < min {
|
||||||
|
fast = proxy
|
||||||
|
min = delay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tolerance
|
||||||
|
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||||
|
u.fastNode = fast
|
||||||
|
}
|
||||||
|
|
||||||
|
return u.fastNode, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.(C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUDP implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) SupportUDP() bool {
|
||||||
|
if u.disableUDP {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return u.fast(false).SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range u.proxies(false) {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": u.Type().String(),
|
||||||
|
"now": u.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseURLTestOption(config map[string]interface{}) []urlTestOption {
|
||||||
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
|
// tolerance
|
||||||
|
if elm, ok := config["tolerance"]; ok {
|
||||||
|
if tolerance, ok := elm.(int); ok {
|
||||||
|
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return opts
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewURLTest(commonOptions *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
|
urlTest := &URLTest{
|
||||||
|
Base: outbound.NewBase(commonOptions.Name, "", C.URLTest, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
fastSingle: singledo.NewSingle(time.Second * 10),
|
||||||
|
providers: providers,
|
||||||
|
disableUDP: commonOptions.DisableUDP,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(urlTest)
|
||||||
|
}
|
||||||
|
|
||||||
|
return urlTest
|
||||||
|
}
|
51
adapter/outboundgroup/util.go
Normal file
51
adapter/outboundgroup/util.go
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
||||||
|
host, port, err := net.SplitHostPort(rawAddress)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("addrToMetadata failed: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip == nil {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: host,
|
||||||
|
DstIP: nil,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv4,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip4,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv6,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
tcp.SetKeepAlive(true)
|
||||||
|
tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
86
adapter/parser.go
Normal file
86
adapter/parser.go
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
package adapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
|
proxyType, existType := mapping["type"].(string)
|
||||||
|
if !existType {
|
||||||
|
return nil, fmt.Errorf("missing type")
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
proxy C.ProxyAdapter
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
switch proxyType {
|
||||||
|
case "ss":
|
||||||
|
ssOption := &outbound.ShadowSocksOption{}
|
||||||
|
err = decoder.Decode(mapping, ssOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewShadowSocks(*ssOption)
|
||||||
|
case "ssr":
|
||||||
|
ssrOption := &outbound.ShadowSocksROption{}
|
||||||
|
err = decoder.Decode(mapping, ssrOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewShadowSocksR(*ssrOption)
|
||||||
|
case "socks5":
|
||||||
|
socksOption := &outbound.Socks5Option{}
|
||||||
|
err = decoder.Decode(mapping, socksOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewSocks5(*socksOption)
|
||||||
|
case "http":
|
||||||
|
httpOption := &outbound.HttpOption{}
|
||||||
|
err = decoder.Decode(mapping, httpOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewHttp(*httpOption)
|
||||||
|
case "vmess":
|
||||||
|
vmessOption := &outbound.VmessOption{
|
||||||
|
HTTPOpts: outbound.HTTPOptions{
|
||||||
|
Method: "GET",
|
||||||
|
Path: []string{"/"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
|
case "snell":
|
||||||
|
snellOption := &outbound.SnellOption{}
|
||||||
|
err = decoder.Decode(mapping, snellOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
|
case "trojan":
|
||||||
|
trojanOption := &outbound.TrojanOption{}
|
||||||
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewProxy(proxy), nil
|
||||||
|
}
|
185
adapter/provider/fetcher.go
Normal file
185
adapter/provider/fetcher.go
Normal file
@ -0,0 +1,185 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
fileMode os.FileMode = 0666
|
||||||
|
dirMode os.FileMode = 0755
|
||||||
|
)
|
||||||
|
|
||||||
|
type parser = func([]byte) (interface{}, error)
|
||||||
|
|
||||||
|
type fetcher struct {
|
||||||
|
name string
|
||||||
|
vehicle types.Vehicle
|
||||||
|
updatedAt *time.Time
|
||||||
|
ticker *time.Ticker
|
||||||
|
done chan struct{}
|
||||||
|
hash [16]byte
|
||||||
|
parser parser
|
||||||
|
onUpdate func(interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Name() string {
|
||||||
|
return f.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) VehicleType() types.VehicleType {
|
||||||
|
return f.vehicle.Type()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Initial() (interface{}, error) {
|
||||||
|
var (
|
||||||
|
buf []byte
|
||||||
|
err error
|
||||||
|
isLocal bool
|
||||||
|
)
|
||||||
|
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
||||||
|
buf, err = ioutil.ReadFile(f.vehicle.Path())
|
||||||
|
modTime := stat.ModTime()
|
||||||
|
f.updatedAt = &modTime
|
||||||
|
isLocal = true
|
||||||
|
} else {
|
||||||
|
buf, err = f.vehicle.Read()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
if !isLocal {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse local file error, fallback to remote
|
||||||
|
buf, err = f.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err = f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
isLocal = false
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.vehicle.Type() != types.File && !isLocal {
|
||||||
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.hash = md5.Sum(buf)
|
||||||
|
|
||||||
|
// pull proxies automatically
|
||||||
|
if f.ticker != nil {
|
||||||
|
go f.pullLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Update() (interface{}, bool, error) {
|
||||||
|
buf, err := f.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
hash := md5.Sum(buf)
|
||||||
|
if bytes.Equal(f.hash[:], hash[:]) {
|
||||||
|
f.updatedAt = &now
|
||||||
|
return nil, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := f.parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.vehicle.Type() != types.File {
|
||||||
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.updatedAt = &now
|
||||||
|
f.hash = hash
|
||||||
|
|
||||||
|
return proxies, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Destroy() error {
|
||||||
|
if f.ticker != nil {
|
||||||
|
f.done <- struct{}{}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) pullLoop() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-f.ticker.C:
|
||||||
|
elm, same, err := f.Update()
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if same {
|
||||||
|
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Infoln("[Provider] %s's proxies update", f.Name())
|
||||||
|
if f.onUpdate != nil {
|
||||||
|
f.onUpdate(elm)
|
||||||
|
}
|
||||||
|
case <-f.done:
|
||||||
|
f.ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeWrite(path string, buf []byte) error {
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
if err := os.MkdirAll(dir, dirMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ioutil.WriteFile(path, buf, fileMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(interface{})) *fetcher {
|
||||||
|
var ticker *time.Ticker
|
||||||
|
if interval != 0 {
|
||||||
|
ticker = time.NewTicker(interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &fetcher{
|
||||||
|
name: name,
|
||||||
|
ticker: ticker,
|
||||||
|
vehicle: vehicle,
|
||||||
|
parser: parser,
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
onUpdate: onUpdate,
|
||||||
|
}
|
||||||
|
}
|
88
adapter/provider/healthcheck.go
Normal file
88
adapter/provider/healthcheck.go
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultURLTestTimeout = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
type HealthCheckOption struct {
|
||||||
|
URL string
|
||||||
|
Interval uint
|
||||||
|
}
|
||||||
|
|
||||||
|
type HealthCheck struct {
|
||||||
|
url string
|
||||||
|
proxies []C.Proxy
|
||||||
|
interval uint
|
||||||
|
lazy bool
|
||||||
|
lastTouch *atomic.Int64
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) process() {
|
||||||
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
|
go hc.check()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
}
|
||||||
|
case <-hc.done:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
|
hc.proxies = proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) auto() bool {
|
||||||
|
return hc.interval != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) touch() {
|
||||||
|
hc.lastTouch.Store(time.Now().Unix())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) check() {
|
||||||
|
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum(10))
|
||||||
|
for _, proxy := range hc.proxies {
|
||||||
|
p := proxy
|
||||||
|
b.Go(p.Name(), func() (interface{}, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
defer cancel()
|
||||||
|
p.URLTest(ctx, hc.url)
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
b.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) close() {
|
||||||
|
hc.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *HealthCheck {
|
||||||
|
return &HealthCheck{
|
||||||
|
proxies: proxies,
|
||||||
|
url: url,
|
||||||
|
interval: interval,
|
||||||
|
lazy: lazy,
|
||||||
|
lastTouch: atomic.NewInt64(0),
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
}
|
@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -17,6 +18,7 @@ type healthCheckSchema struct {
|
|||||||
Enable bool `provider:"enable"`
|
Enable bool `provider:"enable"`
|
||||||
URL string `provider:"url"`
|
URL string `provider:"url"`
|
||||||
Interval int `provider:"interval"`
|
Interval int `provider:"interval"`
|
||||||
|
Lazy bool `provider:"lazy,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
@ -27,23 +29,27 @@ type proxyProviderSchema struct {
|
|||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]interface{}) (ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]interface{}) (types.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{}
|
schema := &proxyProviderSchema{
|
||||||
|
HealthCheck: healthCheckSchema{
|
||||||
|
Lazy: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
if err := decoder.Decode(mapping, schema); err != nil {
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var hcInterval uint = 0
|
var hcInterval uint
|
||||||
if schema.HealthCheck.Enable {
|
if schema.HealthCheck.Enable {
|
||||||
hcInterval = uint(schema.HealthCheck.Interval)
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
}
|
}
|
||||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval)
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
|
||||||
|
|
||||||
path := C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
|
|
||||||
var vehicle Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
vehicle = NewFileVehicle(path)
|
vehicle = NewFileVehicle(path)
|
223
adapter/provider/provider.go
Normal file
223
adapter/provider/provider.go
Normal file
@ -0,0 +1,223 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ReservedName = "default"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProxySchema struct {
|
||||||
|
Proxies []map[string]interface{} `yaml:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// for auto gc
|
||||||
|
type ProxySetProvider struct {
|
||||||
|
*proxySetProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxySetProvider struct {
|
||||||
|
*fetcher
|
||||||
|
proxies []C.Proxy
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"name": pp.Name(),
|
||||||
|
"type": pp.Type().String(),
|
||||||
|
"vehicleType": pp.VehicleType().String(),
|
||||||
|
"proxies": pp.Proxies(),
|
||||||
|
"updatedAt": pp.updatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Name() string {
|
||||||
|
return pp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) HealthCheck() {
|
||||||
|
pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Update() error {
|
||||||
|
elm, same, err := pp.fetcher.Update()
|
||||||
|
if err == nil && !same {
|
||||||
|
pp.onUpdate(elm)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Initial() error {
|
||||||
|
elm, err := pp.fetcher.Initial()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pp.onUpdate(elm)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Type() types.ProviderType {
|
||||||
|
return types.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Proxies() []C.Proxy {
|
||||||
|
return pp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
|
pp.healthCheck.touch()
|
||||||
|
return pp.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
func proxiesParse(buf []byte) (interface{}, 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 {
|
||||||
|
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 {
|
||||||
|
return nil, errors.New("file doesn't have any valid proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
|
pp.proxies = proxies
|
||||||
|
pp.healthCheck.setProxy(proxies)
|
||||||
|
if pp.healthCheck.auto() {
|
||||||
|
go pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
|
pd.healthCheck.close()
|
||||||
|
pd.fetcher.Destroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxySetProvider(name string, interval time.Duration, vehicle types.Vehicle, hc *HealthCheck) *ProxySetProvider {
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
pd := &proxySetProvider{
|
||||||
|
proxies: []C.Proxy{},
|
||||||
|
healthCheck: hc,
|
||||||
|
}
|
||||||
|
|
||||||
|
onUpdate := func(elm interface{}) {
|
||||||
|
ret := elm.([]C.Proxy)
|
||||||
|
pd.setProxies(ret)
|
||||||
|
}
|
||||||
|
|
||||||
|
fetcher := newFetcher(name, interval, vehicle, proxiesParse, onUpdate)
|
||||||
|
pd.fetcher = fetcher
|
||||||
|
|
||||||
|
wrapper := &ProxySetProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
|
return wrapper
|
||||||
|
}
|
||||||
|
|
||||||
|
// for auto gc
|
||||||
|
type CompatibleProvider struct {
|
||||||
|
*compatibleProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type compatibleProvider struct {
|
||||||
|
name string
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
proxies []C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"name": cp.Name(),
|
||||||
|
"type": cp.Type().String(),
|
||||||
|
"vehicleType": cp.VehicleType().String(),
|
||||||
|
"proxies": cp.Proxies(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Name() string {
|
||||||
|
return cp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) HealthCheck() {
|
||||||
|
cp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Update() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Initial() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) VehicleType() types.VehicleType {
|
||||||
|
return types.Compatible
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Type() types.ProviderType {
|
||||||
|
return types.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Proxies() []C.Proxy {
|
||||||
|
return cp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
|
cp.healthCheck.touch()
|
||||||
|
return cp.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
|
pd.healthCheck.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("provider need one proxy at least")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
pd := &compatibleProvider{
|
||||||
|
name: name,
|
||||||
|
proxies: proxies,
|
||||||
|
healthCheck: hc,
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &CompatibleProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||||
|
return wrapper, nil
|
||||||
|
}
|
@ -3,47 +3,21 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Vehicle Type
|
|
||||||
const (
|
|
||||||
File VehicleType = iota
|
|
||||||
HTTP
|
|
||||||
Compatible
|
|
||||||
)
|
|
||||||
|
|
||||||
// VehicleType defined
|
|
||||||
type VehicleType int
|
|
||||||
|
|
||||||
func (v VehicleType) String() string {
|
|
||||||
switch v {
|
|
||||||
case File:
|
|
||||||
return "File"
|
|
||||||
case HTTP:
|
|
||||||
return "HTTP"
|
|
||||||
case Compatible:
|
|
||||||
return "Compatible"
|
|
||||||
default:
|
|
||||||
return "Unknown"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Vehicle interface {
|
|
||||||
Read() ([]byte, error)
|
|
||||||
Path() string
|
|
||||||
Type() VehicleType
|
|
||||||
}
|
|
||||||
|
|
||||||
type FileVehicle struct {
|
type FileVehicle struct {
|
||||||
path string
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FileVehicle) Type() VehicleType {
|
func (f *FileVehicle) Type() types.VehicleType {
|
||||||
return File
|
return types.File
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FileVehicle) Path() string {
|
func (f *FileVehicle) Path() string {
|
||||||
@ -63,8 +37,8 @@ type HTTPVehicle struct {
|
|||||||
path string
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Type() VehicleType {
|
func (h *HTTPVehicle) Type() types.VehicleType {
|
||||||
return HTTP
|
return types.HTTP
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Path() string {
|
func (h *HTTPVehicle) Path() string {
|
||||||
@ -75,10 +49,21 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, h.url, nil)
|
uri, err := url.Parse(h.url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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)
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
transport := &http.Transport{
|
transport := &http.Transport{
|
||||||
@ -87,7 +72,9 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
IdleConnTimeout: 90 * time.Second,
|
IdleConnTimeout: 90 * time.Second,
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: dialer.DialContext,
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{Transport: transport}
|
||||||
@ -95,6 +82,7 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
buf, err := ioutil.ReadAll(resp.Body)
|
buf, err := ioutil.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
@ -1,60 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// HTTPAdapter is a adapter for HTTP connection
|
|
||||||
type HTTPAdapter struct {
|
|
||||||
net.Conn
|
|
||||||
metadata *C.Metadata
|
|
||||||
R *http.Request
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata return destination metadata
|
|
||||||
func (h *HTTPAdapter) Metadata() *C.Metadata {
|
|
||||||
return h.metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewHTTP is HTTPAdapter generator
|
|
||||||
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
|
||||||
metadata := parseHTTPAddr(request)
|
|
||||||
metadata.Type = C.HTTP
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
return &HTTPAdapter{
|
|
||||||
metadata: metadata,
|
|
||||||
R: request,
|
|
||||||
Conn: conn,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoveHopByHopHeaders remove hop-by-hop header
|
|
||||||
func RemoveHopByHopHeaders(header http.Header) {
|
|
||||||
// Strip hop-by-hop header based on RFC:
|
|
||||||
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
|
|
||||||
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
|
|
||||||
|
|
||||||
header.Del("Proxy-Connection")
|
|
||||||
header.Del("Proxy-Authenticate")
|
|
||||||
header.Del("Proxy-Authorization")
|
|
||||||
header.Del("TE")
|
|
||||||
header.Del("Trailers")
|
|
||||||
header.Del("Transfer-Encoding")
|
|
||||||
header.Del("Upgrade")
|
|
||||||
|
|
||||||
connections := header.Get("Connection")
|
|
||||||
header.Del("Connection")
|
|
||||||
if len(connections) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, h := range strings.Split(connections, ",") {
|
|
||||||
header.Del(strings.TrimSpace(h))
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/socks5"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SocketAdapter is a adapter for socks and redir connection
|
|
||||||
type SocketAdapter struct {
|
|
||||||
net.Conn
|
|
||||||
metadata *C.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata return destination metadata
|
|
||||||
func (s *SocketAdapter) Metadata() *C.Metadata {
|
|
||||||
return s.metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSocket is SocketAdapter generator
|
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, netType C.NetWork) *SocketAdapter {
|
|
||||||
metadata := parseSocksAddr(target)
|
|
||||||
metadata.NetWork = netType
|
|
||||||
metadata.Type = source
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
|
|
||||||
return &SocketAdapter{
|
|
||||||
Conn: conn,
|
|
||||||
metadata: metadata,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,64 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) {
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
|
||||||
proxyType, existType := mapping["type"].(string)
|
|
||||||
if !existType {
|
|
||||||
return nil, fmt.Errorf("Missing type")
|
|
||||||
}
|
|
||||||
|
|
||||||
var proxy C.ProxyAdapter
|
|
||||||
err := fmt.Errorf("Cannot parse")
|
|
||||||
switch proxyType {
|
|
||||||
case "ss":
|
|
||||||
ssOption := &ShadowSocksOption{}
|
|
||||||
err = decoder.Decode(mapping, ssOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = NewShadowSocks(*ssOption)
|
|
||||||
case "socks5":
|
|
||||||
socksOption := &Socks5Option{}
|
|
||||||
err = decoder.Decode(mapping, socksOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = NewSocks5(*socksOption)
|
|
||||||
case "http":
|
|
||||||
httpOption := &HttpOption{}
|
|
||||||
err = decoder.Decode(mapping, httpOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = NewHttp(*httpOption)
|
|
||||||
case "vmess":
|
|
||||||
vmessOption := &VmessOption{}
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = NewVmess(*vmessOption)
|
|
||||||
case "snell":
|
|
||||||
snellOption := &SnellOption{}
|
|
||||||
err = decoder.Decode(mapping, snellOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = NewSnell(*snellOption)
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewProxy(proxy), nil
|
|
||||||
}
|
|
@ -1,73 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
|
||||||
"github.com/Dreamacro/clash/component/snell"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Snell struct {
|
|
||||||
*Base
|
|
||||||
server string
|
|
||||||
psk []byte
|
|
||||||
obfsOption *simpleObfsOption
|
|
||||||
}
|
|
||||||
|
|
||||||
type SnellOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Psk string `proxy:"psk"`
|
|
||||||
ObfsOpts map[string]interface{} `proxy:"obfs-opts,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.server)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.server, err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
switch s.obfsOption.Mode {
|
|
||||||
case "tls":
|
|
||||||
c = obfs.NewTLSObfs(c, s.obfsOption.Host)
|
|
||||||
case "http":
|
|
||||||
_, port, _ := net.SplitHostPort(s.server)
|
|
||||||
c = obfs.NewHTTPObfs(c, s.obfsOption.Host, port)
|
|
||||||
}
|
|
||||||
c = snell.StreamConn(c, s.psk)
|
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
err = snell.WriteHeader(c, metadata.String(), uint(port))
|
|
||||||
return newConn(c, s), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
|
||||||
server := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
psk := []byte(option.Psk)
|
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
|
||||||
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
|
||||||
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
|
||||||
return nil, fmt.Errorf("snell %s initialize obfs error: %w", server, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if obfsOption.Mode != "tls" && obfsOption.Mode != "http" {
|
|
||||||
return nil, fmt.Errorf("snell %s obfs mode error: %s", server, obfsOption.Mode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Snell{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Snell,
|
|
||||||
},
|
|
||||||
server: server,
|
|
||||||
psk: psk,
|
|
||||||
obfsOption: obfsOption,
|
|
||||||
}, nil
|
|
||||||
}
|
|
@ -1,146 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
"github.com/Dreamacro/clash/component/vmess"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Vmess struct {
|
|
||||||
*Base
|
|
||||||
server string
|
|
||||||
client *vmess.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
type VmessOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
UUID string `proxy:"uuid"`
|
|
||||||
AlterID int `proxy:"alterId"`
|
|
||||||
Cipher string `proxy:"cipher"`
|
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
Network string `proxy:"network,omitempty"`
|
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.server)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", v.server)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = v.client.New(c, parseVmessAddr(metadata))
|
|
||||||
return newConn(c, v), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
// vmess use stream-oriented udp, so clash needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
|
||||||
defer cancel()
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.server)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", v.server)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = v.client.New(c, parseVmessAddr(metadata))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
|
||||||
}
|
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
|
||||||
security := strings.ToLower(option.Cipher)
|
|
||||||
client, err := vmess.NewClient(vmess.Config{
|
|
||||||
UUID: option.UUID,
|
|
||||||
AlterID: uint16(option.AlterID),
|
|
||||||
Security: security,
|
|
||||||
TLS: option.TLS,
|
|
||||||
HostName: option.Server,
|
|
||||||
Port: strconv.Itoa(option.Port),
|
|
||||||
NetWork: option.Network,
|
|
||||||
WebSocketPath: option.WSPath,
|
|
||||||
WebSocketHeaders: option.WSHeaders,
|
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
|
||||||
SessionCache: getClientSessionCache(),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Vmess{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Vmess,
|
|
||||||
udp: true,
|
|
||||||
},
|
|
||||||
server: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
client: client,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
|
||||||
var addrType byte
|
|
||||||
var addr []byte
|
|
||||||
switch metadata.AddrType {
|
|
||||||
case C.AtypIPv4:
|
|
||||||
addrType = byte(vmess.AtypIPv4)
|
|
||||||
addr = make([]byte, net.IPv4len)
|
|
||||||
copy(addr[:], metadata.DstIP.To4())
|
|
||||||
case C.AtypIPv6:
|
|
||||||
addrType = byte(vmess.AtypIPv6)
|
|
||||||
addr = make([]byte, net.IPv6len)
|
|
||||||
copy(addr[:], metadata.DstIP.To16())
|
|
||||||
case C.AtypDomainName:
|
|
||||||
addrType = byte(vmess.AtypDomainName)
|
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
|
||||||
addr[0] = byte(len(metadata.Host))
|
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
|
||||||
}
|
|
||||||
|
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
return &vmess.DstAddr{
|
|
||||||
UDP: metadata.NetWork == C.UDP,
|
|
||||||
AddrType: addrType,
|
|
||||||
Addr: addr,
|
|
||||||
Port: uint(port),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
|
||||||
net.Conn
|
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
return uc.Conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (uc *vmessPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
|
||||||
return uc.Conn.Write(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (uc *vmessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
n, err := uc.Conn.Read(b)
|
|
||||||
return n, uc.rAddr, err
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/provider"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultGetProxiesDuration = time.Second * 5
|
|
||||||
)
|
|
||||||
|
|
||||||
func getProvidersProxies(providers []provider.ProxyProvider) []C.Proxy {
|
|
||||||
proxies := []C.Proxy{}
|
|
||||||
for _, provider := range providers {
|
|
||||||
proxies = append(proxies, provider.Proxies()...)
|
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
|
@ -1,84 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/outbound"
|
|
||||||
"github.com/Dreamacro/clash/adapters/provider"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Fallback struct {
|
|
||||||
*outbound.Base
|
|
||||||
single *singledo.Single
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
c, err := proxy.DialContext(ctx, metadata)
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(f)
|
|
||||||
}
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
pc, err := proxy.DialUDP(metadata)
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(f)
|
|
||||||
}
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) SupportUDP() bool {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range f.proxies() {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": f.Type().String(),
|
|
||||||
"now": f.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) proxies() []C.Proxy {
|
|
||||||
elm, _, _ := f.single.Do(func() (interface{}, error) {
|
|
||||||
return getProvidersProxies(f.providers), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy() C.Proxy {
|
|
||||||
proxies := f.proxies()
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return f.proxies()[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFallback(name string, providers []provider.ProxyProvider) *Fallback {
|
|
||||||
return &Fallback{
|
|
||||||
Base: outbound.NewBase(name, C.Fallback, false),
|
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,128 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/outbound"
|
|
||||||
"github.com/Dreamacro/clash/adapters/provider"
|
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LoadBalance struct {
|
|
||||||
*outbound.Base
|
|
||||||
single *singledo.Single
|
|
||||||
maxRetry int
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
func getKey(metadata *C.Metadata) string {
|
|
||||||
if metadata.Host != "" {
|
|
||||||
// ip host
|
|
||||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
|
||||||
return metadata.Host
|
|
||||||
}
|
|
||||||
|
|
||||||
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
|
|
||||||
return etld
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if metadata.DstIP == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return metadata.DstIP.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func jumpHash(key uint64, buckets int32) int32 {
|
|
||||||
var b, j int64
|
|
||||||
|
|
||||||
for j < int64(buckets) {
|
|
||||||
b = j
|
|
||||||
key = key*2862933555777941757 + 1
|
|
||||||
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
|
|
||||||
}
|
|
||||||
|
|
||||||
return int32(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
|
||||||
defer func() {
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(lb)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
|
||||||
proxies := lb.proxies()
|
|
||||||
buckets := int32(len(proxies))
|
|
||||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
|
||||||
idx := jumpHash(key, buckets)
|
|
||||||
proxy := proxies[idx]
|
|
||||||
if proxy.Alive() {
|
|
||||||
c, err = proxy.DialContext(ctx, metadata)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err = proxies[0].DialContext(ctx, metadata)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (pc C.PacketConn, err error) {
|
|
||||||
defer func() {
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(lb)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
|
||||||
proxies := lb.proxies()
|
|
||||||
buckets := int32(len(proxies))
|
|
||||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
|
||||||
idx := jumpHash(key, buckets)
|
|
||||||
proxy := proxies[idx]
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy.DialUDP(metadata)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies[0].DialUDP(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) SupportUDP() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) proxies() []C.Proxy {
|
|
||||||
elm, _, _ := lb.single.Do(func() (interface{}, error) {
|
|
||||||
return getProvidersProxies(lb.providers), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range lb.proxies() {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": lb.Type().String(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLoadBalance(name string, providers []provider.ProxyProvider) *LoadBalance {
|
|
||||||
return &LoadBalance{
|
|
||||||
Base: outbound.NewBase(name, C.LoadBalance, false),
|
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
|
||||||
maxRetry: 3,
|
|
||||||
providers: providers,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,85 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/outbound"
|
|
||||||
"github.com/Dreamacro/clash/adapters/provider"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Selector struct {
|
|
||||||
*outbound.Base
|
|
||||||
single *singledo.Single
|
|
||||||
selected C.Proxy
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
c, err := s.selected.DialContext(ctx, metadata)
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(s)
|
|
||||||
}
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
pc, err := s.selected.DialUDP(metadata)
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(s)
|
|
||||||
}
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) SupportUDP() bool {
|
|
||||||
return s.selected.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range s.proxies() {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": s.Type().String(),
|
|
||||||
"now": s.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Now() string {
|
|
||||||
return s.selected.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
|
||||||
for _, proxy := range s.proxies() {
|
|
||||||
if proxy.Name() == name {
|
|
||||||
s.selected = proxy
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return errors.New("Proxy does not exist")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) proxies() []C.Proxy {
|
|
||||||
elm, _, _ := s.single.Do(func() (interface{}, error) {
|
|
||||||
return getProvidersProxies(s.providers), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSelector(name string, providers []provider.ProxyProvider) *Selector {
|
|
||||||
selected := providers[0].Proxies()[0]
|
|
||||||
return &Selector{
|
|
||||||
Base: outbound.NewBase(name, C.Selector, false),
|
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
selected: selected,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,94 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/outbound"
|
|
||||||
"github.com/Dreamacro/clash/adapters/provider"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type URLTest struct {
|
|
||||||
*outbound.Base
|
|
||||||
single *singledo.Single
|
|
||||||
fastSingle *singledo.Single
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
|
||||||
return u.fast().Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
|
||||||
c, err = u.fast().DialContext(ctx, metadata)
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(u)
|
|
||||||
}
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
pc, err := u.fast().DialUDP(metadata)
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(u)
|
|
||||||
}
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) proxies() []C.Proxy {
|
|
||||||
elm, _, _ := u.single.Do(func() (interface{}, error) {
|
|
||||||
return getProvidersProxies(u.providers), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) fast() C.Proxy {
|
|
||||||
elm, _, _ := u.fastSingle.Do(func() (interface{}, error) {
|
|
||||||
proxies := u.proxies()
|
|
||||||
fast := proxies[0]
|
|
||||||
min := fast.LastDelay()
|
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
if !proxy.Alive() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
delay := proxy.LastDelay()
|
|
||||||
if delay < min {
|
|
||||||
fast = proxy
|
|
||||||
min = delay
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fast, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm.(C.Proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) SupportUDP() bool {
|
|
||||||
return u.fast().SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range u.proxies() {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": u.Type().String(),
|
|
||||||
"now": u.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewURLTest(name string, providers []provider.ProxyProvider) *URLTest {
|
|
||||||
return &URLTest{
|
|
||||||
Base: outbound.NewBase(name, C.URLTest, false),
|
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
|
||||||
fastSingle: singledo.NewSingle(time.Second * 10),
|
|
||||||
providers: providers,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,70 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultURLTestTimeout = time.Second * 5
|
|
||||||
)
|
|
||||||
|
|
||||||
type HealthCheckOption struct {
|
|
||||||
URL string
|
|
||||||
Interval uint
|
|
||||||
}
|
|
||||||
|
|
||||||
type HealthCheck struct {
|
|
||||||
url string
|
|
||||||
proxies []C.Proxy
|
|
||||||
interval uint
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
|
||||||
|
|
||||||
go hc.check()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ticker.C:
|
|
||||||
hc.check()
|
|
||||||
case <-hc.done:
|
|
||||||
ticker.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
|
||||||
hc.proxies = proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) auto() bool {
|
|
||||||
return hc.interval != 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
|
||||||
for _, proxy := range hc.proxies {
|
|
||||||
go proxy.URLTest(ctx, hc.url)
|
|
||||||
}
|
|
||||||
|
|
||||||
<-ctx.Done()
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
|
||||||
hc.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHealthCheck(proxies []C.Proxy, url string, interval uint) *HealthCheck {
|
|
||||||
return &HealthCheck{
|
|
||||||
proxies: proxies,
|
|
||||||
url: url,
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}, 1),
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,322 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/md5"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/outbound"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
ReservedName = "default"
|
|
||||||
|
|
||||||
fileMode = 0666
|
|
||||||
)
|
|
||||||
|
|
||||||
// Provider Type
|
|
||||||
const (
|
|
||||||
Proxy ProviderType = iota
|
|
||||||
Rule
|
|
||||||
)
|
|
||||||
|
|
||||||
// ProviderType defined
|
|
||||||
type ProviderType int
|
|
||||||
|
|
||||||
func (pt ProviderType) String() string {
|
|
||||||
switch pt {
|
|
||||||
case Proxy:
|
|
||||||
return "Proxy"
|
|
||||||
case Rule:
|
|
||||||
return "Rule"
|
|
||||||
default:
|
|
||||||
return "Unknown"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provider interface
|
|
||||||
type Provider interface {
|
|
||||||
Name() string
|
|
||||||
VehicleType() VehicleType
|
|
||||||
Type() ProviderType
|
|
||||||
Initial() error
|
|
||||||
Reload() error
|
|
||||||
Destroy() error
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProxyProvider interface
|
|
||||||
type ProxyProvider interface {
|
|
||||||
Provider
|
|
||||||
Proxies() []C.Proxy
|
|
||||||
HealthCheck()
|
|
||||||
Update() error
|
|
||||||
}
|
|
||||||
|
|
||||||
type ProxySchema struct {
|
|
||||||
Proxies []map[string]interface{} `yaml:"proxies"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ProxySetProvider struct {
|
|
||||||
name string
|
|
||||||
vehicle Vehicle
|
|
||||||
hash [16]byte
|
|
||||||
proxies []C.Proxy
|
|
||||||
healthCheck *HealthCheck
|
|
||||||
ticker *time.Ticker
|
|
||||||
updatedAt *time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"name": pp.Name(),
|
|
||||||
"type": pp.Type().String(),
|
|
||||||
"vehicleType": pp.VehicleType().String(),
|
|
||||||
"proxies": pp.Proxies(),
|
|
||||||
"updatedAt": pp.updatedAt,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Name() string {
|
|
||||||
return pp.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Reload() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) HealthCheck() {
|
|
||||||
pp.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Update() error {
|
|
||||||
return pp.pull()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Destroy() error {
|
|
||||||
pp.healthCheck.close()
|
|
||||||
|
|
||||||
if pp.ticker != nil {
|
|
||||||
pp.ticker.Stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Initial() error {
|
|
||||||
var buf []byte
|
|
||||||
var err error
|
|
||||||
if stat, err := os.Stat(pp.vehicle.Path()); err == nil {
|
|
||||||
buf, err = ioutil.ReadFile(pp.vehicle.Path())
|
|
||||||
modTime := stat.ModTime()
|
|
||||||
pp.updatedAt = &modTime
|
|
||||||
} else {
|
|
||||||
buf, err = pp.vehicle.Read()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := pp.parse(buf)
|
|
||||||
if err != nil {
|
|
||||||
// parse local file error, fallback to remote
|
|
||||||
buf, err = pp.vehicle.Read()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
pp.hash = md5.Sum(buf)
|
|
||||||
pp.setProxies(proxies)
|
|
||||||
|
|
||||||
// pull proxies automatically
|
|
||||||
if pp.ticker != nil {
|
|
||||||
go pp.pullLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) VehicleType() VehicleType {
|
|
||||||
return pp.vehicle.Type()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Type() ProviderType {
|
|
||||||
return Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) Proxies() []C.Proxy {
|
|
||||||
return pp.proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) pullLoop() {
|
|
||||||
for range pp.ticker.C {
|
|
||||||
if err := pp.pull(); err != nil {
|
|
||||||
log.Warnln("[Provider] %s pull error: %s", pp.Name(), err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) pull() error {
|
|
||||||
buf, err := pp.vehicle.Read()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
hash := md5.Sum(buf)
|
|
||||||
if bytes.Equal(pp.hash[:], hash[:]) {
|
|
||||||
log.Debugln("[Provider] %s's proxies doesn't change", pp.Name())
|
|
||||||
pp.updatedAt = &now
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := pp.parse(buf)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Infoln("[Provider] %s's proxies update", pp.Name())
|
|
||||||
|
|
||||||
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
pp.updatedAt = &now
|
|
||||||
pp.hash = hash
|
|
||||||
pp.setProxies(proxies)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) parse(buf []byte) ([]C.Proxy, 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 {
|
|
||||||
proxy, err := outbound.ParseProxy(mapping)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Proxy %d error: %w", idx, err)
|
|
||||||
}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("File doesn't have any valid proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *ProxySetProvider) setProxies(proxies []C.Proxy) {
|
|
||||||
pp.proxies = proxies
|
|
||||||
pp.healthCheck.setProxy(proxies)
|
|
||||||
go pp.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, vehicle Vehicle, hc *HealthCheck) *ProxySetProvider {
|
|
||||||
var ticker *time.Ticker
|
|
||||||
if interval != 0 {
|
|
||||||
ticker = time.NewTicker(interval)
|
|
||||||
}
|
|
||||||
|
|
||||||
if hc.auto() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
return &ProxySetProvider{
|
|
||||||
name: name,
|
|
||||||
vehicle: vehicle,
|
|
||||||
proxies: []C.Proxy{},
|
|
||||||
healthCheck: hc,
|
|
||||||
ticker: ticker,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type CompatibleProvider struct {
|
|
||||||
name string
|
|
||||||
healthCheck *HealthCheck
|
|
||||||
proxies []C.Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"name": cp.Name(),
|
|
||||||
"type": cp.Type().String(),
|
|
||||||
"vehicleType": cp.VehicleType().String(),
|
|
||||||
"proxies": cp.Proxies(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Name() string {
|
|
||||||
return cp.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Reload() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Destroy() error {
|
|
||||||
cp.healthCheck.close()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) HealthCheck() {
|
|
||||||
cp.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Update() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Initial() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) VehicleType() VehicleType {
|
|
||||||
return Compatible
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Type() ProviderType {
|
|
||||||
return Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *CompatibleProvider) Proxies() []C.Proxy {
|
|
||||||
return cp.proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("Provider need one proxy at least")
|
|
||||||
}
|
|
||||||
|
|
||||||
if hc.auto() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
return &CompatibleProvider{
|
|
||||||
name: name,
|
|
||||||
proxies: proxies,
|
|
||||||
healthCheck: hc,
|
|
||||||
}, nil
|
|
||||||
}
|
|
105
common/batch/batch.go
Normal file
105
common/batch/batch.go
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
package batch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Option = func(b *Batch)
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Value interface{}
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Error struct {
|
||||||
|
Key string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithConcurrencyNum(n int) Option {
|
||||||
|
return func(b *Batch) {
|
||||||
|
q := make(chan struct{}, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
q <- struct{}{}
|
||||||
|
}
|
||||||
|
b.queue = q
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Batch similar to errgroup, but can control the maximum number of concurrent
|
||||||
|
type Batch struct {
|
||||||
|
result map[string]Result
|
||||||
|
queue chan struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
mux sync.Mutex
|
||||||
|
err *Error
|
||||||
|
once sync.Once
|
||||||
|
cancel func()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch) Go(key string, fn func() (interface{}, error)) {
|
||||||
|
b.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer b.wg.Done()
|
||||||
|
if b.queue != nil {
|
||||||
|
<-b.queue
|
||||||
|
defer func() {
|
||||||
|
b.queue <- struct{}{}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
value, err := fn()
|
||||||
|
if err != nil {
|
||||||
|
b.once.Do(func() {
|
||||||
|
b.err = &Error{key, err}
|
||||||
|
if b.cancel != nil {
|
||||||
|
b.cancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
ret := Result{value, err}
|
||||||
|
b.mux.Lock()
|
||||||
|
defer b.mux.Unlock()
|
||||||
|
b.result[key] = ret
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch) Wait() *Error {
|
||||||
|
b.wg.Wait()
|
||||||
|
if b.cancel != nil {
|
||||||
|
b.cancel()
|
||||||
|
}
|
||||||
|
return b.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch) WaitAndGetResult() (map[string]Result, *Error) {
|
||||||
|
err := b.Wait()
|
||||||
|
return b.Result(), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Batch) Result() map[string]Result {
|
||||||
|
b.mux.Lock()
|
||||||
|
defer b.mux.Unlock()
|
||||||
|
copy := map[string]Result{}
|
||||||
|
for k, v := range b.result {
|
||||||
|
copy[k] = v
|
||||||
|
}
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(ctx context.Context, opts ...Option) (*Batch, context.Context) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
|
||||||
|
b := &Batch{
|
||||||
|
result: map[string]Result{},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range opts {
|
||||||
|
o(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
b.cancel = cancel
|
||||||
|
return b, ctx
|
||||||
|
}
|
83
common/batch/batch_test.go
Normal file
83
common/batch/batch_test.go
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
package batch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBatch(t *testing.T) {
|
||||||
|
b, _ := New(context.Background())
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
b.Go("foo", func() (interface{}, error) {
|
||||||
|
time.Sleep(time.Millisecond * 100)
|
||||||
|
return "foo", nil
|
||||||
|
})
|
||||||
|
b.Go("bar", func() (interface{}, error) {
|
||||||
|
time.Sleep(time.Millisecond * 150)
|
||||||
|
return "bar", nil
|
||||||
|
})
|
||||||
|
result, err := b.WaitAndGetResult()
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
duration := time.Since(now)
|
||||||
|
assert.Less(t, duration, time.Millisecond*200)
|
||||||
|
assert.Equal(t, 2, len(result))
|
||||||
|
|
||||||
|
for k, v := range result {
|
||||||
|
assert.NoError(t, v.Err)
|
||||||
|
assert.Equal(t, k, v.Value.(string))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBatchWithConcurrencyNum(t *testing.T) {
|
||||||
|
b, _ := New(
|
||||||
|
context.Background(),
|
||||||
|
WithConcurrencyNum(3),
|
||||||
|
)
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
for i := 0; i < 7; i++ {
|
||||||
|
idx := i
|
||||||
|
b.Go(strconv.Itoa(idx), func() (interface{}, error) {
|
||||||
|
time.Sleep(time.Millisecond * 100)
|
||||||
|
return strconv.Itoa(idx), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
result, _ := b.WaitAndGetResult()
|
||||||
|
duration := time.Since(now)
|
||||||
|
assert.Greater(t, duration, time.Millisecond*260)
|
||||||
|
assert.Equal(t, 7, len(result))
|
||||||
|
|
||||||
|
for k, v := range result {
|
||||||
|
assert.NoError(t, v.Err)
|
||||||
|
assert.Equal(t, k, v.Value.(string))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBatchContext(t *testing.T) {
|
||||||
|
b, ctx := New(context.Background())
|
||||||
|
|
||||||
|
b.Go("error", func() (interface{}, error) {
|
||||||
|
time.Sleep(time.Millisecond * 100)
|
||||||
|
return nil, errors.New("test error")
|
||||||
|
})
|
||||||
|
|
||||||
|
b.Go("ctx", func() (interface{}, error) {
|
||||||
|
<-ctx.Done()
|
||||||
|
return nil, ctx.Err()
|
||||||
|
})
|
||||||
|
|
||||||
|
result, err := b.WaitAndGetResult()
|
||||||
|
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
assert.Equal(t, "error", err.Key)
|
||||||
|
|
||||||
|
assert.Equal(t, ctx.Err(), result["ctx"].Err)
|
||||||
|
}
|
102
common/cache/lrucache.go
vendored
102
common/cache/lrucache.go
vendored
@ -42,6 +42,14 @@ func WithSize(maxSize int) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithStale decide whether Stale return is enabled.
|
||||||
|
// If this feature is enabled, element will not get Evicted according to `WithAge`.
|
||||||
|
func WithStale(stale bool) Option {
|
||||||
|
return func(l *LruCache) {
|
||||||
|
l.staleReturn = stale
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// LruCache is a thread-safe, in-memory lru-cache that evicts the
|
// LruCache is a thread-safe, in-memory lru-cache that evicts the
|
||||||
// least recently used entries from memory when (if set) the entries are
|
// least recently used entries from memory when (if set) the entries are
|
||||||
// older than maxAge (in seconds). Use the New constructor to create one.
|
// older than maxAge (in seconds). Use the New constructor to create one.
|
||||||
@ -52,6 +60,7 @@ type LruCache struct {
|
|||||||
cache map[interface{}]*list.Element
|
cache map[interface{}]*list.Element
|
||||||
lru *list.List // Front is least-recent
|
lru *list.List // Front is least-recent
|
||||||
updateAgeOnGet bool
|
updateAgeOnGet bool
|
||||||
|
staleReturn bool
|
||||||
onEvict EvictCallback
|
onEvict EvictCallback
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,31 +81,28 @@ func NewLRUCache(options ...Option) *LruCache {
|
|||||||
// Get returns the interface{} representation of a cached response and a bool
|
// Get returns the interface{} representation of a cached response and a bool
|
||||||
// set to true if the key was found.
|
// set to true if the key was found.
|
||||||
func (c *LruCache) Get(key interface{}) (interface{}, bool) {
|
func (c *LruCache) Get(key interface{}) (interface{}, bool) {
|
||||||
c.mu.Lock()
|
entry := c.get(key)
|
||||||
defer c.mu.Unlock()
|
if entry == nil {
|
||||||
|
|
||||||
le, ok := c.cache[key]
|
|
||||||
if !ok {
|
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.maxAge > 0 && le.Value.(*entry).expires <= time.Now().Unix() {
|
|
||||||
c.deleteElement(le)
|
|
||||||
c.maybeDeleteOldest()
|
|
||||||
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
c.lru.MoveToBack(le)
|
|
||||||
entry := le.Value.(*entry)
|
|
||||||
if c.maxAge > 0 && c.updateAgeOnGet {
|
|
||||||
entry.expires = time.Now().Unix() + c.maxAge
|
|
||||||
}
|
|
||||||
value := entry.value
|
value := entry.value
|
||||||
|
|
||||||
return value, true
|
return value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetWithExpire returns the interface{} representation of a cached response,
|
||||||
|
// a time.Time Give expected expires,
|
||||||
|
// and a bool set to true if the key was found.
|
||||||
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
|
func (c *LruCache) GetWithExpire(key interface{}) (interface{}, time.Time, bool) {
|
||||||
|
entry := c.get(key)
|
||||||
|
if entry == nil {
|
||||||
|
return nil, time.Time{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return entry.value, time.Unix(entry.expires, 0), true
|
||||||
|
}
|
||||||
|
|
||||||
// Exist returns if key exist in cache but not put item to the head of linked list
|
// Exist returns if key exist in cache but not put item to the head of linked list
|
||||||
func (c *LruCache) Exist(key interface{}) bool {
|
func (c *LruCache) Exist(key interface{}) bool {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@ -108,21 +114,26 @@ func (c *LruCache) Exist(key interface{}) bool {
|
|||||||
|
|
||||||
// Set stores the interface{} representation of a response for a given key.
|
// Set stores the interface{} representation of a response for a given key.
|
||||||
func (c *LruCache) Set(key interface{}, value interface{}) {
|
func (c *LruCache) Set(key interface{}, value interface{}) {
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
expires := int64(0)
|
expires := int64(0)
|
||||||
if c.maxAge > 0 {
|
if c.maxAge > 0 {
|
||||||
expires = time.Now().Unix() + c.maxAge
|
expires = time.Now().Unix() + c.maxAge
|
||||||
}
|
}
|
||||||
|
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetWithExpire stores the interface{} representation of a response for a given key and given expires.
|
||||||
|
// The expires time will round to second.
|
||||||
|
func (c *LruCache) SetWithExpire(key interface{}, value interface{}, expires time.Time) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
c.lru.MoveToBack(le)
|
c.lru.MoveToBack(le)
|
||||||
e := le.Value.(*entry)
|
e := le.Value.(*entry)
|
||||||
e.value = value
|
e.value = value
|
||||||
e.expires = expires
|
e.expires = expires.Unix()
|
||||||
} else {
|
} else {
|
||||||
e := &entry{key: key, value: value, expires: expires}
|
e := &entry{key: key, value: value, expires: expires.Unix()}
|
||||||
c.cache[key] = c.lru.PushBack(e)
|
c.cache[key] = c.lru.PushBack(e)
|
||||||
|
|
||||||
if c.maxSize > 0 {
|
if c.maxSize > 0 {
|
||||||
@ -135,8 +146,49 @@ func (c *LruCache) Set(key interface{}, value interface{}) {
|
|||||||
c.maybeDeleteOldest()
|
c.maybeDeleteOldest()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CloneTo clone and overwrite elements to another LruCache
|
||||||
|
func (c *LruCache) CloneTo(n *LruCache) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
n.mu.Lock()
|
||||||
|
defer n.mu.Unlock()
|
||||||
|
|
||||||
|
n.lru = list.New()
|
||||||
|
n.cache = make(map[interface{}]*list.Element)
|
||||||
|
|
||||||
|
for e := c.lru.Front(); e != nil; e = e.Next() {
|
||||||
|
elm := e.Value.(*entry)
|
||||||
|
n.cache[elm.key] = n.lru.PushBack(elm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache) get(key interface{}) *entry {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
le, ok := c.cache[key]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if !c.staleReturn && c.maxAge > 0 && le.Value.(*entry).expires <= time.Now().Unix() {
|
||||||
|
c.deleteElement(le)
|
||||||
|
c.maybeDeleteOldest()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c.lru.MoveToBack(le)
|
||||||
|
entry := le.Value.(*entry)
|
||||||
|
if c.maxAge > 0 && c.updateAgeOnGet {
|
||||||
|
entry.expires = time.Now().Unix() + c.maxAge
|
||||||
|
}
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
|
||||||
// Delete removes the value associated with a key.
|
// Delete removes the value associated with a key.
|
||||||
func (c *LruCache) Delete(key string) {
|
func (c *LruCache) Delete(key interface{}) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
@ -147,7 +199,7 @@ func (c *LruCache) Delete(key string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache) maybeDeleteOldest() {
|
func (c *LruCache) maybeDeleteOldest() {
|
||||||
if c.maxAge > 0 {
|
if !c.staleReturn && c.maxAge > 0 {
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
for le := c.lru.Front(); le != nil && le.Value.(*entry).expires <= now; le = c.lru.Front() {
|
for le := c.lru.Front(); le != nil && le.Value.(*entry).expires <= now; le = c.lru.Front() {
|
||||||
c.deleteElement(le)
|
c.deleteElement(le)
|
||||||
|
46
common/cache/lrucache_test.go
vendored
46
common/cache/lrucache_test.go
vendored
@ -136,3 +136,49 @@ func TestEvict(t *testing.T) {
|
|||||||
|
|
||||||
assert.Equal(t, temp, 3)
|
assert.Equal(t, temp, 3)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSetWithExpire(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithAge(1))
|
||||||
|
now := time.Now().Unix()
|
||||||
|
|
||||||
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
|
c.SetWithExpire(1, 2, tenSecBefore)
|
||||||
|
|
||||||
|
// res is expected not to exist, and expires should be empty time.Time
|
||||||
|
res, expires, exist := c.GetWithExpire(1)
|
||||||
|
assert.Equal(t, nil, res)
|
||||||
|
assert.Equal(t, time.Time{}, expires)
|
||||||
|
assert.Equal(t, false, exist)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStale(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithAge(1), WithStale(true))
|
||||||
|
now := time.Now().Unix()
|
||||||
|
|
||||||
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
|
c.SetWithExpire(1, 2, tenSecBefore)
|
||||||
|
|
||||||
|
res, expires, exist := c.GetWithExpire(1)
|
||||||
|
assert.Equal(t, 2, res)
|
||||||
|
assert.Equal(t, tenSecBefore, expires)
|
||||||
|
assert.Equal(t, true, exist)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCloneTo(t *testing.T) {
|
||||||
|
o := NewLRUCache(WithSize(10))
|
||||||
|
o.Set("1", 1)
|
||||||
|
o.Set("2", 2)
|
||||||
|
|
||||||
|
n := NewLRUCache(WithSize(2))
|
||||||
|
n.Set("3", 3)
|
||||||
|
n.Set("4", 4)
|
||||||
|
|
||||||
|
o.CloneTo(n)
|
||||||
|
|
||||||
|
assert.False(t, n.Exist("3"))
|
||||||
|
assert.True(t, n.Exist("1"))
|
||||||
|
|
||||||
|
n.Set("5", 5)
|
||||||
|
assert.False(t, n.Exist("1"))
|
||||||
|
}
|
||||||
|
41
common/net/bufconn.go
Normal file
41
common/net/bufconn.go
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BufferedConn struct {
|
||||||
|
r *bufio.Reader
|
||||||
|
net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBufferedConn(c net.Conn) *BufferedConn {
|
||||||
|
return &BufferedConn{bufio.NewReader(c), c}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reader returns the internal bufio.Reader.
|
||||||
|
func (c *BufferedConn) Reader() *bufio.Reader {
|
||||||
|
return c.r
|
||||||
|
}
|
||||||
|
|
||||||
|
// Peek returns the next n bytes without advancing the reader.
|
||||||
|
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
||||||
|
return c.r.Peek(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Read(p []byte) (int, error) {
|
||||||
|
return c.r.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ReadByte() (byte, error) {
|
||||||
|
return c.r.ReadByte()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) UnreadByte() error {
|
||||||
|
return c.r.UnreadByte()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Buffered() int {
|
||||||
|
return c.r.Buffered()
|
||||||
|
}
|
11
common/net/io.go
Normal file
11
common/net/io.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import "io"
|
||||||
|
|
||||||
|
type ReadOnlyReader struct {
|
||||||
|
io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
type WriteOnlyWriter struct {
|
||||||
|
io.Writer
|
||||||
|
}
|
@ -1,12 +1,12 @@
|
|||||||
package observable
|
package observable
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"runtime"
|
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator(item []interface{}) chan interface{} {
|
func iterator(item []interface{}) chan interface{} {
|
||||||
@ -33,25 +33,25 @@ func TestObservable(t *testing.T) {
|
|||||||
assert.Equal(t, count, 5)
|
assert.Equal(t, count, 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_MutilSubscribe(t *testing.T) {
|
func TestObservable_MultiSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
ch1, _ := src.Subscribe()
|
ch1, _ := src.Subscribe()
|
||||||
ch2, _ := src.Subscribe()
|
ch2, _ := src.Subscribe()
|
||||||
count := 0
|
var count = atomic.NewInt32(0)
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan interface{}) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count++
|
count.Inc()
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
go waitCh(ch1)
|
go waitCh(ch1)
|
||||||
go waitCh(ch2)
|
go waitCh(ch2)
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
assert.Equal(t, count, 10)
|
assert.Equal(t, int32(10), count.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribe(t *testing.T) {
|
func TestObservable_UnSubscribe(t *testing.T) {
|
||||||
@ -82,9 +82,6 @@ func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
||||||
// waiting for other goroutine recycle
|
|
||||||
time.Sleep(120 * time.Millisecond)
|
|
||||||
init := runtime.NumGoroutine()
|
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
max := 100
|
max := 100
|
||||||
@ -107,6 +104,43 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
go waitCh(ch)
|
go waitCh(ch)
|
||||||
}
|
}
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
now := runtime.NumGoroutine()
|
|
||||||
assert.Equal(t, init, now)
|
for _, sub := range list {
|
||||||
|
_, more := <-sub
|
||||||
|
assert.False(t, more)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, more := <-list[0]
|
||||||
|
assert.False(t, more)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Benchmark_Observable_1000(b *testing.B) {
|
||||||
|
ch := make(chan interface{})
|
||||||
|
o := NewObservable(ch)
|
||||||
|
num := 1000
|
||||||
|
|
||||||
|
subs := []Subscription{}
|
||||||
|
for i := 0; i < num; i++ {
|
||||||
|
sub, _ := o.Subscribe()
|
||||||
|
subs = append(subs, sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(num)
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for _, sub := range subs {
|
||||||
|
go func(s Subscription) {
|
||||||
|
for range s {
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}(sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
ch <- i
|
||||||
|
}
|
||||||
|
|
||||||
|
close(ch)
|
||||||
|
wg.Wait()
|
||||||
}
|
}
|
||||||
|
@ -2,34 +2,32 @@ package observable
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"gopkg.in/eapache/channels.v1"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Subscription <-chan interface{}
|
type Subscription <-chan interface{}
|
||||||
|
|
||||||
type Subscriber struct {
|
type Subscriber struct {
|
||||||
buffer *channels.InfiniteChannel
|
buffer chan interface{}
|
||||||
once sync.Once
|
once sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Emit(item interface{}) {
|
func (s *Subscriber) Emit(item interface{}) {
|
||||||
s.buffer.In() <- item
|
s.buffer <- item
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Out() Subscription {
|
func (s *Subscriber) Out() Subscription {
|
||||||
return s.buffer.Out()
|
return s.buffer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Close() {
|
func (s *Subscriber) Close() {
|
||||||
s.once.Do(func() {
|
s.once.Do(func() {
|
||||||
s.buffer.Close()
|
close(s.buffer)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func newSubscriber() *Subscriber {
|
func newSubscriber() *Subscriber {
|
||||||
sub := &Subscriber{
|
sub := &Subscriber{
|
||||||
buffer: channels.NewInfiniteChannel(),
|
buffer: make(chan interface{}, 200),
|
||||||
}
|
}
|
||||||
return sub
|
return sub
|
||||||
}
|
}
|
||||||
|
@ -15,8 +15,10 @@ type Picker struct {
|
|||||||
|
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
|
|
||||||
once sync.Once
|
once sync.Once
|
||||||
result interface{}
|
errOnce sync.Once
|
||||||
|
result interface{}
|
||||||
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPicker(ctx context.Context, cancel func()) *Picker {
|
func newPicker(ctx context.Context, cancel func()) *Picker {
|
||||||
@ -49,6 +51,11 @@ func (p *Picker) Wait() interface{} {
|
|||||||
return p.result
|
return p.result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error return the first error (if all success return nil)
|
||||||
|
func (p *Picker) Error() error {
|
||||||
|
return p.err
|
||||||
|
}
|
||||||
|
|
||||||
// Go calls the given function in a new goroutine.
|
// Go calls the given function in a new goroutine.
|
||||||
// The first call to return a nil error cancels the group; its result will be returned by Wait.
|
// The first call to return a nil error cancels the group; its result will be returned by Wait.
|
||||||
func (p *Picker) Go(f func() (interface{}, error)) {
|
func (p *Picker) Go(f func() (interface{}, error)) {
|
||||||
@ -64,6 +71,10 @@ func (p *Picker) Go(f func() (interface{}, error)) {
|
|||||||
p.cancel()
|
p.cancel()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
} else {
|
||||||
|
p.errOnce.Do(func() {
|
||||||
|
p.err = err
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
@ -36,4 +36,5 @@ func TestPicker_Timeout(t *testing.T) {
|
|||||||
|
|
||||||
number := picker.Wait()
|
number := picker.Wait()
|
||||||
assert.Nil(t, number)
|
assert.Nil(t, number)
|
||||||
|
assert.NotNil(t, picker.Error())
|
||||||
}
|
}
|
||||||
|
63
common/pool/alloc.go
Normal file
63
common/pool/alloc.go
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
// Inspired by https://github.com/xtaci/smux/blob/master/alloc.go
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"math/bits"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var defaultAllocator = NewAllocator()
|
||||||
|
|
||||||
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
|
type Allocator struct {
|
||||||
|
buffers []sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
|
||||||
|
// the waste(memory fragmentation) of space allocation is guaranteed to be
|
||||||
|
// no more than 50%.
|
||||||
|
func NewAllocator() *Allocator {
|
||||||
|
alloc := new(Allocator)
|
||||||
|
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
||||||
|
for k := range alloc.buffers {
|
||||||
|
i := k
|
||||||
|
alloc.buffers[k].New = func() interface{} {
|
||||||
|
return make([]byte, 1<<uint32(i))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return alloc
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get a []byte from pool with most appropriate cap
|
||||||
|
func (alloc *Allocator) Get(size int) []byte {
|
||||||
|
if size <= 0 || size > 65536 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
bits := msb(size)
|
||||||
|
if size == 1<<bits {
|
||||||
|
return alloc.buffers[bits].Get().([]byte)[:size]
|
||||||
|
}
|
||||||
|
|
||||||
|
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put returns a []byte to pool for future use,
|
||||||
|
// which the cap must be exactly 2^n
|
||||||
|
func (alloc *Allocator) Put(buf []byte) error {
|
||||||
|
bits := msb(cap(buf))
|
||||||
|
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
|
||||||
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
|
}
|
||||||
|
|
||||||
|
//lint:ignore SA6002 ignore temporarily
|
||||||
|
alloc.buffers[bits].Put(buf)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// msb return the pos of most significant bit
|
||||||
|
func msb(size int) uint16 {
|
||||||
|
return uint16(bits.Len32(uint32(size)) - 1)
|
||||||
|
}
|
48
common/pool/alloc_test.go
Normal file
48
common/pool/alloc_test.go
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAllocGet(t *testing.T) {
|
||||||
|
alloc := NewAllocator()
|
||||||
|
assert.Nil(t, alloc.Get(0))
|
||||||
|
assert.Equal(t, 1, len(alloc.Get(1)))
|
||||||
|
assert.Equal(t, 2, len(alloc.Get(2)))
|
||||||
|
assert.Equal(t, 3, len(alloc.Get(3)))
|
||||||
|
assert.Equal(t, 4, cap(alloc.Get(3)))
|
||||||
|
assert.Equal(t, 4, cap(alloc.Get(4)))
|
||||||
|
assert.Equal(t, 1023, len(alloc.Get(1023)))
|
||||||
|
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
||||||
|
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
||||||
|
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
||||||
|
assert.Nil(t, alloc.Get(65537))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAllocPut(t *testing.T) {
|
||||||
|
alloc := NewAllocator()
|
||||||
|
assert.NotNil(t, alloc.Put(nil), "put nil misbehavior")
|
||||||
|
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
|
||||||
|
assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
|
||||||
|
assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
|
||||||
|
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
|
||||||
|
assert.NotNil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAllocPutThenGet(t *testing.T) {
|
||||||
|
alloc := NewAllocator()
|
||||||
|
data := alloc.Get(4)
|
||||||
|
alloc.Put(data)
|
||||||
|
newData := alloc.Get(4)
|
||||||
|
|
||||||
|
assert.Equal(t, cap(data), cap(newData), "different cap while alloc.Get()")
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkMSB(b *testing.B) {
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
msb(rand.Int())
|
||||||
|
}
|
||||||
|
}
|
@ -1,15 +1,16 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// io.Copy default buffer size is 32 KiB
|
// io.Copy default buffer size is 32 KiB
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
bufferSize = 20 * 1024
|
RelayBufferSize = 20 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
// BufPool provide buffer for relay
|
func Get(size int) []byte {
|
||||||
var BufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
|
return defaultAllocator.Get(size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Put(buf []byte) error {
|
||||||
|
return defaultAllocator.Put(buf)
|
||||||
|
}
|
||||||
|
@ -24,6 +24,8 @@ type Result struct {
|
|||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Do single.Do likes sync.singleFlight
|
||||||
|
//lint:ignore ST1008 it likes sync.singleFlight
|
||||||
func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
|
func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
|
||||||
s.mux.Lock()
|
s.mux.Lock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
@ -44,12 +46,19 @@ func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, s
|
|||||||
s.mux.Unlock()
|
s.mux.Unlock()
|
||||||
call.val, call.err = fn()
|
call.val, call.err = fn()
|
||||||
call.wg.Done()
|
call.wg.Done()
|
||||||
|
|
||||||
|
s.mux.Lock()
|
||||||
s.call = nil
|
s.call = nil
|
||||||
s.result = &Result{call.val, call.err}
|
s.result = &Result{call.val, call.err}
|
||||||
s.last = now
|
s.last = now
|
||||||
|
s.mux.Unlock()
|
||||||
return call.val, call.err, false
|
return call.val, call.err, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Single) Reset() {
|
||||||
|
s.last = time.Time{}
|
||||||
|
}
|
||||||
|
|
||||||
func NewSingle(wait time.Duration) *Single {
|
func NewSingle(wait time.Duration) *Single {
|
||||||
return &Single{wait: wait}
|
return &Single{wait: wait}
|
||||||
}
|
}
|
||||||
|
@ -6,12 +6,13 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBasic(t *testing.T) {
|
func TestBasic(t *testing.T) {
|
||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
shardCount := 0
|
var shardCount = atomic.NewInt32(0)
|
||||||
call := func() (interface{}, error) {
|
call := func() (interface{}, error) {
|
||||||
foo++
|
foo++
|
||||||
time.Sleep(time.Millisecond * 5)
|
time.Sleep(time.Millisecond * 5)
|
||||||
@ -19,13 +20,13 @@ func TestBasic(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
const n = 10
|
const n = 5
|
||||||
wg.Add(n)
|
wg.Add(n)
|
||||||
for i := 0; i < n; i++ {
|
for i := 0; i < n; i++ {
|
||||||
go func() {
|
go func() {
|
||||||
_, _, shard := single.Do(call)
|
_, _, shard := single.Do(call)
|
||||||
if shard {
|
if shard {
|
||||||
shardCount++
|
shardCount.Inc()
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
@ -33,7 +34,7 @@ func TestBasic(t *testing.T) {
|
|||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
assert.Equal(t, 1, foo)
|
assert.Equal(t, 1, foo)
|
||||||
assert.Equal(t, 9, shardCount)
|
assert.Equal(t, int32(4), shardCount.Load())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTimer(t *testing.T) {
|
func TestTimer(t *testing.T) {
|
||||||
@ -51,3 +52,18 @@ func TestTimer(t *testing.T) {
|
|||||||
assert.Equal(t, 1, foo)
|
assert.Equal(t, 1, foo)
|
||||||
assert.True(t, shard)
|
assert.True(t, shard)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReset(t *testing.T) {
|
||||||
|
single := NewSingle(time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
call := func() (interface{}, error) {
|
||||||
|
foo++
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
single.Do(call)
|
||||||
|
single.Reset()
|
||||||
|
single.Do(call)
|
||||||
|
|
||||||
|
assert.Equal(t, 2, foo)
|
||||||
|
}
|
||||||
|
19
common/sockopt/reuseaddr_linux.go
Normal file
19
common/sockopt/reuseaddr_linux.go
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package sockopt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func UDPReuseaddr(c *net.UDPConn) (err error) {
|
||||||
|
rc, err := c.SyscallConn()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rc.Control(func(fd uintptr) {
|
||||||
|
err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
12
common/sockopt/reuseaddr_other.go
Normal file
12
common/sockopt/reuseaddr_other.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build !linux
|
||||||
|
// +build !linux
|
||||||
|
|
||||||
|
package sockopt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
func UDPReuseaddr(c *net.UDPConn) (err error) {
|
||||||
|
return
|
||||||
|
}
|
@ -216,6 +216,11 @@ func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val refle
|
|||||||
}
|
}
|
||||||
|
|
||||||
v := dataVal.MapIndex(k).Interface()
|
v := dataVal.MapIndex(k).Interface()
|
||||||
|
if v == nil {
|
||||||
|
errors = append(errors, fmt.Sprintf("filed %s invalid", fieldName))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
currentVal := reflect.Indirect(reflect.New(valElemType))
|
currentVal := reflect.Indirect(reflect.New(valElemType))
|
||||||
if err := d.decode(fieldName, v, currentVal); err != nil {
|
if err := d.decode(fieldName, v, currentVal); err != nil {
|
||||||
errors = append(errors, err.Error())
|
errors = append(errors, err.Error())
|
||||||
|
18
component/dhcp/conn.go
Normal file
18
component/dhcp/conn.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package dhcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ListenDHCPClient(ctx context.Context, ifaceName string) (net.PacketConn, error) {
|
||||||
|
listenAddr := "0.0.0.0:68"
|
||||||
|
if runtime.GOOS == "linux" || runtime.GOOS == "android" {
|
||||||
|
listenAddr = "255.255.255.255:68"
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialer.ListenPacket(ctx, "udp4", listenAddr, dialer.WithInterface(ifaceName), dialer.WithAddrReuse(true))
|
||||||
|
}
|
94
component/dhcp/dhcp.go
Normal file
94
component/dhcp/dhcp.go
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
package dhcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/insomniacslk/dhcp/dhcpv4"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNotResponding = errors.New("DHCP not responding")
|
||||||
|
ErrNotFound = errors.New("DNS option not found")
|
||||||
|
)
|
||||||
|
|
||||||
|
func ResolveDNSFromDHCP(context context.Context, ifaceName string) ([]net.IP, error) {
|
||||||
|
conn, err := ListenDHCPClient(context, ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
result := make(chan []net.IP, 1)
|
||||||
|
|
||||||
|
discovery, err := dhcpv4.NewDiscovery(randomHardware(), dhcpv4.WithBroadcast(true), dhcpv4.WithRequestedOptions(dhcpv4.OptionDomainNameServer))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
go receiveOffer(conn, discovery.TransactionID, result)
|
||||||
|
|
||||||
|
_, err = conn.WriteTo(discovery.ToBytes(), &net.UDPAddr{IP: net.IPv4bcast, Port: 67})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case r, ok := <-result:
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
case <-context.Done():
|
||||||
|
return nil, ErrNotResponding
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func receiveOffer(conn net.PacketConn, id dhcpv4.TransactionID, result chan<- []net.IP) {
|
||||||
|
defer close(result)
|
||||||
|
|
||||||
|
buf := make([]byte, dhcpv4.MaxMessageSize)
|
||||||
|
|
||||||
|
for {
|
||||||
|
n, _, err := conn.ReadFrom(buf)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pkt, err := dhcpv4.FromBytes(buf[:n])
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if pkt.MessageType() != dhcpv4.MessageTypeOffer {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if pkt.TransactionID != id {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
dns := pkt.DNS()
|
||||||
|
if len(dns) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result <- dns
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomHardware() net.HardwareAddr {
|
||||||
|
addr := make(net.HardwareAddr, 6)
|
||||||
|
|
||||||
|
addr[0] = 0xff
|
||||||
|
|
||||||
|
for i := 1; i < len(addr); i++ {
|
||||||
|
addr[i] = byte(rand.Intn(254) + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return addr
|
||||||
|
}
|
59
component/dialer/bind_darwin.go
Normal file
59
component/dialer/bind_darwin.go
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
)
|
||||||
|
|
||||||
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
||||||
|
|
||||||
|
func bindControl(ifaceIdx int, chain controlFn) controlFn {
|
||||||
|
return func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
ipStr, _, err := net.SplitHostPort(address)
|
||||||
|
if err == nil {
|
||||||
|
ip := net.ParseIP(ipStr)
|
||||||
|
if ip != nil && !ip.IsGlobalUnicast() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Control(func(fd uintptr) {
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifaceIdx)
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifaceIdx)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ net.IP) error {
|
||||||
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
lc.Control = bindControl(ifaceObj.Index, lc.Control)
|
||||||
|
return address, nil
|
||||||
|
}
|
44
component/dialer/bind_linux.go
Normal file
44
component/dialer/bind_linux.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
||||||
|
|
||||||
|
func bindControl(ifaceName string, chain controlFn) controlFn {
|
||||||
|
return func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
ipStr, _, err := net.SplitHostPort(address)
|
||||||
|
if err == nil {
|
||||||
|
ip := net.ParseIP(ipStr)
|
||||||
|
if ip != nil && !ip.IsGlobalUnicast() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Control(func(fd uintptr) {
|
||||||
|
unix.BindToDevice(int(fd), ifaceName)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ net.IP) error {
|
||||||
|
dialer.Control = bindControl(ifaceName, dialer.Control)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
|
lc.Control = bindControl(ifaceName, lc.Control)
|
||||||
|
|
||||||
|
return address, nil
|
||||||
|
}
|
93
component/dialer/bind_others.go
Normal file
93
component/dialer/bind_others.go
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
//go:build !linux && !darwin
|
||||||
|
// +build !linux,!darwin
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
)
|
||||||
|
|
||||||
|
func lookupLocalAddr(ifaceName string, network string, destination net.IP, port int) (net.Addr, error) {
|
||||||
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var addr *net.IPNet
|
||||||
|
switch network {
|
||||||
|
case "udp4", "tcp4":
|
||||||
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
|
default:
|
||||||
|
if destination != nil {
|
||||||
|
if destination.To4() != nil {
|
||||||
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
|
} else {
|
||||||
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(network, "tcp") {
|
||||||
|
return &net.TCPAddr{
|
||||||
|
IP: addr.IP,
|
||||||
|
Port: port,
|
||||||
|
}, nil
|
||||||
|
} else if strings.HasPrefix(network, "udp") {
|
||||||
|
return &net.UDPAddr{
|
||||||
|
IP: addr.IP,
|
||||||
|
Port: port,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, iface.ErrAddrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination net.IP) error {
|
||||||
|
if !destination.IsGlobalUnicast() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
local := 0
|
||||||
|
if dialer.LocalAddr != nil {
|
||||||
|
_, port, err := net.SplitHostPort(dialer.LocalAddr.String())
|
||||||
|
if err == nil {
|
||||||
|
local, _ = strconv.Atoi(port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := lookupLocalAddr(ifaceName, network, destination, local)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer.LocalAddr = addr
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string) (string, error) {
|
||||||
|
_, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
port = "0"
|
||||||
|
}
|
||||||
|
|
||||||
|
local, _ := strconv.Atoi(port)
|
||||||
|
|
||||||
|
addr, err := lookupLocalAddr(ifaceName, network, nil, local)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return addr.String(), nil
|
||||||
|
}
|
@ -8,29 +8,7 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Dialer() *net.Dialer {
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
|
||||||
if DialerHook != nil {
|
|
||||||
DialerHook(dialer)
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialer
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenConfig() *net.ListenConfig {
|
|
||||||
cfg := &net.ListenConfig{}
|
|
||||||
if ListenConfigHook != nil {
|
|
||||||
ListenConfigHook(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
return cfg
|
|
||||||
}
|
|
||||||
|
|
||||||
func Dial(network, address string) (net.Conn, error) {
|
|
||||||
return DialContext(context.Background(), network, address)
|
|
||||||
}
|
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
@ -38,8 +16,6 @@ func DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
dialer := Dialer()
|
|
||||||
|
|
||||||
var ip net.IP
|
var ip net.IP
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "udp4":
|
case "tcp4", "udp4":
|
||||||
@ -47,35 +23,70 @@ func DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
|||||||
default:
|
default:
|
||||||
ip, err = resolver.ResolveIPv6(host)
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if DialHook != nil {
|
return dialContext(ctx, network, ip, port, options)
|
||||||
DialHook(dialer, network, ip)
|
|
||||||
}
|
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
|
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return dualStackDailContext(ctx, network, address)
|
return dualStackDialContext(ctx, network, address, options)
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("network invalid")
|
return nil, errors.New("network invalid")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ListenPacket(network, address string) (net.PacketConn, error) {
|
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
||||||
lc := ListenConfig()
|
cfg := &config{}
|
||||||
|
|
||||||
if ListenPacketHook != nil && address == "" {
|
if !cfg.skipDefault {
|
||||||
ip := ListenPacketHook()
|
for _, o := range DefaultOptions {
|
||||||
if ip != nil {
|
o(cfg)
|
||||||
address = net.JoinHostPort(ip.String(), "0")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return lc.ListenPacket(context.Background(), network, address)
|
|
||||||
|
for _, o := range options {
|
||||||
|
o(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
lc := &net.ListenConfig{}
|
||||||
|
if cfg.interfaceName != "" {
|
||||||
|
addr, err := bindIfaceToListenConfig(cfg.interfaceName, lc, network, address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
address = addr
|
||||||
|
}
|
||||||
|
if cfg.addrReuse {
|
||||||
|
addrReuseToListenConfig(lc)
|
||||||
|
}
|
||||||
|
|
||||||
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func dualStackDailContext(ctx context.Context, network, address string) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination net.IP, port string, options []Option) (net.Conn, error) {
|
||||||
|
opt := &config{}
|
||||||
|
|
||||||
|
if !opt.skipDefault {
|
||||||
|
for _, o := range DefaultOptions {
|
||||||
|
o(opt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range options {
|
||||||
|
o(opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer := &net.Dialer{}
|
||||||
|
if opt.interfaceName != "" {
|
||||||
|
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
|
}
|
||||||
|
|
||||||
|
func dualStackDialContext(ctx context.Context, network, address string, options []Option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -95,7 +106,6 @@ func dualStackDailContext(ctx context.Context, network, address string) (net.Con
|
|||||||
var primary, fallback dialResult
|
var primary, fallback dialResult
|
||||||
|
|
||||||
startRacer := func(ctx context.Context, network, host string, ipv6 bool) {
|
startRacer := func(ctx context.Context, network, host string, ipv6 bool) {
|
||||||
dialer := Dialer()
|
|
||||||
result := dialResult{ipv6: ipv6, done: true}
|
result := dialResult{ipv6: ipv6, done: true}
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
@ -118,37 +128,33 @@ func dualStackDailContext(ctx context.Context, network, address string) (net.Con
|
|||||||
}
|
}
|
||||||
result.resolved = true
|
result.resolved = true
|
||||||
|
|
||||||
if DialHook != nil {
|
result.Conn, result.error = dialContext(ctx, network, ip, port, options)
|
||||||
DialHook(dialer, network, ip)
|
|
||||||
}
|
|
||||||
result.Conn, result.error = dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
go startRacer(ctx, network+"4", host, false)
|
go startRacer(ctx, network+"4", host, false)
|
||||||
go startRacer(ctx, network+"6", host, true)
|
go startRacer(ctx, network+"6", host, true)
|
||||||
|
|
||||||
for {
|
for res := range results {
|
||||||
select {
|
if res.error == nil {
|
||||||
case res := <-results:
|
return res.Conn, nil
|
||||||
if res.error == nil {
|
}
|
||||||
return res.Conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !res.ipv6 {
|
if !res.ipv6 {
|
||||||
primary = res
|
primary = res
|
||||||
|
} else {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
|
||||||
|
if primary.done && fallback.done {
|
||||||
|
if primary.resolved {
|
||||||
|
return nil, primary.error
|
||||||
|
} else if fallback.resolved {
|
||||||
|
return nil, fallback.error
|
||||||
} else {
|
} else {
|
||||||
fallback = res
|
return nil, primary.error
|
||||||
}
|
|
||||||
|
|
||||||
if primary.done && fallback.done {
|
|
||||||
if primary.resolved {
|
|
||||||
return nil, primary.error
|
|
||||||
} else if fallback.resolved {
|
|
||||||
return nil, fallback.error
|
|
||||||
} else {
|
|
||||||
return nil, primary.error
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return nil, errors.New("never touched")
|
||||||
}
|
}
|
||||||
|
@ -1,142 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DialerHookFunc = func(dialer *net.Dialer)
|
|
||||||
type DialHookFunc = func(dialer *net.Dialer, network string, ip net.IP)
|
|
||||||
type ListenConfigHookFunc = func(*net.ListenConfig)
|
|
||||||
type ListenPacketHookFunc = func() net.IP
|
|
||||||
|
|
||||||
var (
|
|
||||||
DialerHook DialerHookFunc
|
|
||||||
DialHook DialHookFunc
|
|
||||||
ListenConfigHook ListenConfigHookFunc
|
|
||||||
ListenPacketHook ListenPacketHookFunc
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrAddrNotFound = errors.New("addr not found")
|
|
||||||
ErrNetworkNotSupport = errors.New("network not support")
|
|
||||||
)
|
|
||||||
|
|
||||||
func lookupTCPAddr(ip net.IP, addrs []net.Addr) (*net.TCPAddr, error) {
|
|
||||||
ipv4 := ip.To4() != nil
|
|
||||||
|
|
||||||
for _, elm := range addrs {
|
|
||||||
addr, ok := elm.(*net.IPNet)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
addrV4 := addr.IP.To4() != nil
|
|
||||||
|
|
||||||
if addrV4 && ipv4 {
|
|
||||||
return &net.TCPAddr{IP: addr.IP, Port: 0}, nil
|
|
||||||
} else if !addrV4 && !ipv4 {
|
|
||||||
return &net.TCPAddr{IP: addr.IP, Port: 0}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, ErrAddrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
func lookupUDPAddr(ip net.IP, addrs []net.Addr) (*net.UDPAddr, error) {
|
|
||||||
ipv4 := ip.To4() != nil
|
|
||||||
|
|
||||||
for _, elm := range addrs {
|
|
||||||
addr, ok := elm.(*net.IPNet)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
addrV4 := addr.IP.To4() != nil
|
|
||||||
|
|
||||||
if addrV4 && ipv4 {
|
|
||||||
return &net.UDPAddr{IP: addr.IP, Port: 0}, nil
|
|
||||||
} else if !addrV4 && !ipv4 {
|
|
||||||
return &net.UDPAddr{IP: addr.IP, Port: 0}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, ErrAddrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenPacketWithInterface(name string) ListenPacketHookFunc {
|
|
||||||
single := singledo.NewSingle(5 * time.Second)
|
|
||||||
|
|
||||||
return func() net.IP {
|
|
||||||
elm, err, _ := single.Do(func() (interface{}, error) {
|
|
||||||
iface, err := net.InterfaceByName(name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addrs, err := iface.Addrs()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return addrs, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
addrs := elm.([]net.Addr)
|
|
||||||
|
|
||||||
for _, elm := range addrs {
|
|
||||||
addr, ok := elm.(*net.IPNet)
|
|
||||||
if !ok || addr.IP.To4() == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return addr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func DialerWithInterface(name string) DialHookFunc {
|
|
||||||
single := singledo.NewSingle(5 * time.Second)
|
|
||||||
|
|
||||||
return func(dialer *net.Dialer, network string, ip net.IP) {
|
|
||||||
elm, err, _ := single.Do(func() (interface{}, error) {
|
|
||||||
iface, err := net.InterfaceByName(name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addrs, err := iface.Addrs()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return addrs, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addrs := elm.([]net.Addr)
|
|
||||||
|
|
||||||
switch network {
|
|
||||||
case "tcp", "tcp4", "tcp6":
|
|
||||||
if addr, err := lookupTCPAddr(ip, addrs); err == nil {
|
|
||||||
dialer.LocalAddr = addr
|
|
||||||
}
|
|
||||||
case "udp", "udp4", "udp6":
|
|
||||||
if addr, err := lookupUDPAddr(ip, addrs); err == nil {
|
|
||||||
dialer.LocalAddr = addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
31
component/dialer/options.go
Normal file
31
component/dialer/options.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
var (
|
||||||
|
DefaultOptions []Option
|
||||||
|
)
|
||||||
|
|
||||||
|
type config struct {
|
||||||
|
skipDefault bool
|
||||||
|
interfaceName string
|
||||||
|
addrReuse bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option func(opt *config)
|
||||||
|
|
||||||
|
func WithInterface(name string) Option {
|
||||||
|
return func(opt *config) {
|
||||||
|
opt.interfaceName = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithAddrReuse(reuse bool) Option {
|
||||||
|
return func(opt *config) {
|
||||||
|
opt.addrReuse = reuse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSkipDefault(skip bool) Option {
|
||||||
|
return func(opt *config) {
|
||||||
|
opt.skipDefault = skip
|
||||||
|
}
|
||||||
|
}
|
10
component/dialer/reuse_others.go
Normal file
10
component/dialer/reuse_others.go
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows
|
||||||
|
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addrReuseToListenConfig(*net.ListenConfig) {}
|
28
component/dialer/reuse_unix.go
Normal file
28
component/dialer/reuse_unix.go
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||||
|
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||||
|
chain := lc.Control
|
||||||
|
|
||||||
|
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return c.Control(func(fd uintptr) {
|
||||||
|
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
|
||||||
|
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
24
component/dialer/reuse_windows.go
Normal file
24
component/dialer/reuse_windows.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||||
|
chain := lc.Control
|
||||||
|
|
||||||
|
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return c.Control(func(fd uintptr) {
|
||||||
|
windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -1,92 +0,0 @@
|
|||||||
package trie
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
wildcard = "*"
|
|
||||||
domainStep = "."
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ErrInvalidDomain means insert domain is invalid
|
|
||||||
ErrInvalidDomain = errors.New("invalid domain")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Trie contains the main logic for adding and searching nodes for domain segments.
|
|
||||||
// support wildcard domain (e.g *.google.com)
|
|
||||||
type Trie struct {
|
|
||||||
root *Node
|
|
||||||
}
|
|
||||||
|
|
||||||
func isValidDomain(domain string) bool {
|
|
||||||
return domain != "" && domain[0] != '.' && domain[len(domain)-1] != '.'
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert adds a node to the trie.
|
|
||||||
// Support
|
|
||||||
// 1. www.example.com
|
|
||||||
// 2. *.example.com
|
|
||||||
// 3. subdomain.*.example.com
|
|
||||||
func (t *Trie) Insert(domain string, data interface{}) error {
|
|
||||||
if !isValidDomain(domain) {
|
|
||||||
return ErrInvalidDomain
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(domain, domainStep)
|
|
||||||
node := t.root
|
|
||||||
// reverse storage domain part to save space
|
|
||||||
for i := len(parts) - 1; i >= 0; i-- {
|
|
||||||
part := parts[i]
|
|
||||||
if !node.hasChild(part) {
|
|
||||||
node.addChild(part, newNode(nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
node = node.getChild(part)
|
|
||||||
}
|
|
||||||
|
|
||||||
node.Data = data
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Search is the most important part of the Trie.
|
|
||||||
// Priority as:
|
|
||||||
// 1. static part
|
|
||||||
// 2. wildcard domain
|
|
||||||
func (t *Trie) Search(domain string) *Node {
|
|
||||||
if !isValidDomain(domain) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
parts := strings.Split(domain, domainStep)
|
|
||||||
|
|
||||||
n := t.root
|
|
||||||
for i := len(parts) - 1; i >= 0; i-- {
|
|
||||||
part := parts[i]
|
|
||||||
|
|
||||||
var child *Node
|
|
||||||
if !n.hasChild(part) {
|
|
||||||
if !n.hasChild(wildcard) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
child = n.getChild(wildcard)
|
|
||||||
} else {
|
|
||||||
child = n.getChild(part)
|
|
||||||
}
|
|
||||||
|
|
||||||
n = child
|
|
||||||
}
|
|
||||||
|
|
||||||
if n.Data == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a new, empty Trie.
|
|
||||||
func New() *Trie {
|
|
||||||
return &Trie{root: newNode(nil)}
|
|
||||||
}
|
|
@ -1,87 +0,0 @@
|
|||||||
package trie
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
var localIP = net.IP{127, 0, 0, 1}
|
|
||||||
|
|
||||||
func TestTrie_Basic(t *testing.T) {
|
|
||||||
tree := New()
|
|
||||||
domains := []string{
|
|
||||||
"example.com",
|
|
||||||
"google.com",
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, domain := range domains {
|
|
||||||
tree.Insert(domain, localIP)
|
|
||||||
}
|
|
||||||
|
|
||||||
node := tree.Search("example.com")
|
|
||||||
if node == nil {
|
|
||||||
t.Error("should not recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if !node.Data.(net.IP).Equal(localIP) {
|
|
||||||
t.Error("should equal 127.0.0.1")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Insert("", localIP) == nil {
|
|
||||||
t.Error("should return error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTrie_Wildcard(t *testing.T) {
|
|
||||||
tree := New()
|
|
||||||
domains := []string{
|
|
||||||
"*.example.com",
|
|
||||||
"sub.*.example.com",
|
|
||||||
"*.dev",
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, domain := range domains {
|
|
||||||
tree.Insert(domain, localIP)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search("sub.example.com") == nil {
|
|
||||||
t.Error("should not recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search("sub.foo.example.com") == nil {
|
|
||||||
t.Error("should not recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search("foo.sub.example.com") != nil {
|
|
||||||
t.Error("should recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search("foo.example.dev") != nil {
|
|
||||||
t.Error("should recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search("example.com") != nil {
|
|
||||||
t.Error("should recv nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTrie_Boundary(t *testing.T) {
|
|
||||||
tree := New()
|
|
||||||
tree.Insert("*.dev", localIP)
|
|
||||||
|
|
||||||
if err := tree.Insert(".", localIP); err == nil {
|
|
||||||
t.Error("should recv err")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := tree.Insert(".com", localIP); err == nil {
|
|
||||||
t.Error("should recv err")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search("dev") != nil {
|
|
||||||
t.Error("should recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if tree.Search(".dev") != nil {
|
|
||||||
t.Error("should recv nil")
|
|
||||||
}
|
|
||||||
}
|
|
@ -6,7 +6,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
trie "github.com/Dreamacro/clash/component/domain-trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pool is a implementation about fake ip generator without storage
|
// Pool is a implementation about fake ip generator without storage
|
||||||
@ -16,7 +16,8 @@ type Pool struct {
|
|||||||
gateway uint32
|
gateway uint32
|
||||||
offset uint32
|
offset uint32
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
host *trie.Trie
|
host *trie.DomainTrie
|
||||||
|
ipnet *net.IPNet
|
||||||
cache *cache.LruCache
|
cache *cache.LruCache
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,6 +90,16 @@ func (p *Pool) Gateway() net.IP {
|
|||||||
return uintToIP(p.gateway)
|
return uintToIP(p.gateway)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IPNet return raw ipnet
|
||||||
|
func (p *Pool) IPNet() *net.IPNet {
|
||||||
|
return p.ipnet
|
||||||
|
}
|
||||||
|
|
||||||
|
// PatchFrom clone cache from old pool
|
||||||
|
func (p *Pool) PatchFrom(o *Pool) {
|
||||||
|
o.cache.CloneTo(p.cache)
|
||||||
|
}
|
||||||
|
|
||||||
func (p *Pool) get(host string) net.IP {
|
func (p *Pool) get(host string) net.IP {
|
||||||
current := p.offset
|
current := p.offset
|
||||||
for {
|
for {
|
||||||
@ -116,11 +127,11 @@ func ipToUint(ip net.IP) uint32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func uintToIP(v uint32) net.IP {
|
func uintToIP(v uint32) net.IP {
|
||||||
return net.IPv4(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
|
return net.IP{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)}
|
||||||
}
|
}
|
||||||
|
|
||||||
// New return Pool instance
|
// New return Pool instance
|
||||||
func New(ipnet *net.IPNet, size int, host *trie.Trie) (*Pool, error) {
|
func New(ipnet *net.IPNet, size int, host *trie.DomainTrie) (*Pool, error) {
|
||||||
min := ipToUint(ipnet.IP) + 2
|
min := ipToUint(ipnet.IP) + 2
|
||||||
|
|
||||||
ones, bits := ipnet.Mask.Size()
|
ones, bits := ipnet.Mask.Size()
|
||||||
@ -136,6 +147,7 @@ func New(ipnet *net.IPNet, size int, host *trie.Trie) (*Pool, error) {
|
|||||||
max: max,
|
max: max,
|
||||||
gateway: min - 1,
|
gateway: min - 1,
|
||||||
host: host,
|
host: host,
|
||||||
|
ipnet: ipnet,
|
||||||
cache: cache.NewLRUCache(cache.WithSize(size * 2)),
|
cache: cache.NewLRUCache(cache.WithSize(size * 2)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
113
component/iface/iface.go
Normal file
113
component/iface/iface.go
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
package iface
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Interface struct {
|
||||||
|
Index int
|
||||||
|
Name string
|
||||||
|
Addrs []*net.IPNet
|
||||||
|
HardwareAddr net.HardwareAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrIfaceNotFound = errors.New("interface not found")
|
||||||
|
var ErrAddrNotFound = errors.New("addr not found")
|
||||||
|
|
||||||
|
var interfaces = singledo.NewSingle(time.Second * 20)
|
||||||
|
|
||||||
|
func ResolveInterface(name string) (*Interface, error) {
|
||||||
|
value, err, _ := interfaces.Do(func() (interface{}, error) {
|
||||||
|
ifaces, err := net.Interfaces()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
r := map[string]*Interface{}
|
||||||
|
|
||||||
|
for _, iface := range ifaces {
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
ipNets := make([]*net.IPNet, 0, len(addrs))
|
||||||
|
for _, addr := range addrs {
|
||||||
|
ipNet := addr.(*net.IPNet)
|
||||||
|
if v4 := ipNet.IP.To4(); v4 != nil {
|
||||||
|
ipNet.IP = v4
|
||||||
|
}
|
||||||
|
|
||||||
|
ipNets = append(ipNets, ipNet)
|
||||||
|
}
|
||||||
|
|
||||||
|
r[iface.Name] = &Interface{
|
||||||
|
Index: iface.Index,
|
||||||
|
Name: iface.Name,
|
||||||
|
Addrs: ipNets,
|
||||||
|
HardwareAddr: iface.HardwareAddr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ifaces := value.(map[string]*Interface)
|
||||||
|
iface, ok := ifaces[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrIfaceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return iface, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func FlushCache() {
|
||||||
|
interfaces.Reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iface *Interface) PickIPv4Addr(destination net.IP) (*net.IPNet, error) {
|
||||||
|
return iface.pickIPAddr(destination, func(addr *net.IPNet) bool {
|
||||||
|
return addr.IP.To4() != nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iface *Interface) PickIPv6Addr(destination net.IP) (*net.IPNet, error) {
|
||||||
|
return iface.pickIPAddr(destination, func(addr *net.IPNet) bool {
|
||||||
|
return addr.IP.To4() == nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (iface *Interface) pickIPAddr(destination net.IP, accept func(addr *net.IPNet) bool) (*net.IPNet, error) {
|
||||||
|
var fallback *net.IPNet
|
||||||
|
|
||||||
|
for _, addr := range iface.Addrs {
|
||||||
|
if !accept(addr) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback == nil && !addr.IP.IsLinkLocalUnicast() {
|
||||||
|
fallback = addr
|
||||||
|
|
||||||
|
if destination == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if destination != nil && addr.Contains(destination) {
|
||||||
|
return addr, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback == nil {
|
||||||
|
return nil, ErrAddrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback, nil
|
||||||
|
}
|
@ -22,6 +22,14 @@ func LoadFromBytes(buffer []byte) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Verify() bool {
|
||||||
|
instance, err := geoip2.Open(C.Path.MMDB())
|
||||||
|
if err == nil {
|
||||||
|
instance.Close()
|
||||||
|
}
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
func Instance() *geoip2.Reader {
|
func Instance() *geoip2.Reader {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
var err error
|
var err error
|
||||||
|
@ -22,9 +22,9 @@ func (t *Table) Get(key string) C.PacketConn {
|
|||||||
return item.(C.PacketConn)
|
return item.(C.PacketConn)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Table) GetOrCreateLock(key string) (*sync.WaitGroup, bool) {
|
func (t *Table) GetOrCreateLock(key string) (*sync.Cond, bool) {
|
||||||
item, loaded := t.mapping.LoadOrStore(key, &sync.WaitGroup{})
|
item, loaded := t.mapping.LoadOrStore(key, sync.NewCond(&sync.Mutex{}))
|
||||||
return item.(*sync.WaitGroup), loaded
|
return item.(*sync.Cond), loaded
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Table) Delete(key string) {
|
func (t *Table) Delete(key string) {
|
||||||
|
114
component/pool/pool.go
Normal file
114
component/pool/pool.go
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Factory = func(context.Context) (interface{}, error)
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
elm interface{}
|
||||||
|
time time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option func(*pool)
|
||||||
|
|
||||||
|
// WithEvict set the evict callback
|
||||||
|
func WithEvict(cb func(interface{})) Option {
|
||||||
|
return func(p *pool) {
|
||||||
|
p.evict = cb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithAge defined element max age (millisecond)
|
||||||
|
func WithAge(maxAge int64) Option {
|
||||||
|
return func(p *pool) {
|
||||||
|
p.maxAge = maxAge
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithSize defined max size of Pool
|
||||||
|
func WithSize(maxSize int) Option {
|
||||||
|
return func(p *pool) {
|
||||||
|
p.ch = make(chan interface{}, maxSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pool is for GC, see New for detail
|
||||||
|
type Pool struct {
|
||||||
|
*pool
|
||||||
|
}
|
||||||
|
|
||||||
|
type pool struct {
|
||||||
|
ch chan interface{}
|
||||||
|
factory Factory
|
||||||
|
evict func(interface{})
|
||||||
|
maxAge int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pool) GetContext(ctx context.Context) (interface{}, error) {
|
||||||
|
now := time.Now()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case item := <-p.ch:
|
||||||
|
elm := item.(*entry)
|
||||||
|
if p.maxAge != 0 && now.Sub(item.(*entry).time).Milliseconds() > p.maxAge {
|
||||||
|
if p.evict != nil {
|
||||||
|
p.evict(elm.elm)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return elm.elm, nil
|
||||||
|
default:
|
||||||
|
return p.factory(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pool) Get() (interface{}, error) {
|
||||||
|
return p.GetContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pool) Put(item interface{}) {
|
||||||
|
e := &entry{
|
||||||
|
elm: item,
|
||||||
|
time: time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case p.ch <- e:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
// pool is full
|
||||||
|
if p.evict != nil {
|
||||||
|
p.evict(item)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func recycle(p *Pool) {
|
||||||
|
for item := range p.pool.ch {
|
||||||
|
if p.pool.evict != nil {
|
||||||
|
p.pool.evict(item.(*entry).elm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(factory Factory, options ...Option) *Pool {
|
||||||
|
p := &pool{
|
||||||
|
ch: make(chan interface{}, 10),
|
||||||
|
factory: factory,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
P := &Pool{p}
|
||||||
|
runtime.SetFinalizer(P, recycle)
|
||||||
|
return P
|
||||||
|
}
|
73
component/pool/pool_test.go
Normal file
73
component/pool/pool_test.go
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func lg() Factory {
|
||||||
|
initial := -1
|
||||||
|
return func(context.Context) (interface{}, error) {
|
||||||
|
initial++
|
||||||
|
return initial, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_Basic(t *testing.T) {
|
||||||
|
g := lg()
|
||||||
|
pool := New(g)
|
||||||
|
|
||||||
|
elm, _ := pool.Get()
|
||||||
|
assert.Equal(t, 0, elm.(int))
|
||||||
|
pool.Put(elm)
|
||||||
|
elm, _ = pool.Get()
|
||||||
|
assert.Equal(t, 0, elm.(int))
|
||||||
|
elm, _ = pool.Get()
|
||||||
|
assert.Equal(t, 1, elm.(int))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_MaxSize(t *testing.T) {
|
||||||
|
g := lg()
|
||||||
|
size := 5
|
||||||
|
pool := New(g, WithSize(size))
|
||||||
|
|
||||||
|
items := []interface{}{}
|
||||||
|
|
||||||
|
for i := 0; i < size; i++ {
|
||||||
|
item, _ := pool.Get()
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
extra, _ := pool.Get()
|
||||||
|
assert.Equal(t, size, extra.(int))
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
pool.Put(item)
|
||||||
|
}
|
||||||
|
|
||||||
|
pool.Put(extra)
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
elm, _ := pool.Get()
|
||||||
|
assert.Equal(t, item.(int), elm.(int))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_MaxAge(t *testing.T) {
|
||||||
|
g := lg()
|
||||||
|
pool := New(g, WithAge(20))
|
||||||
|
|
||||||
|
elm, _ := pool.Get()
|
||||||
|
pool.Put(elm)
|
||||||
|
|
||||||
|
elm, _ = pool.Get()
|
||||||
|
assert.Equal(t, 0, elm.(int))
|
||||||
|
pool.Put(elm)
|
||||||
|
|
||||||
|
time.Sleep(time.Millisecond * 22)
|
||||||
|
elm, _ = pool.Get()
|
||||||
|
assert.Equal(t, 1, elm.(int))
|
||||||
|
}
|
21
component/process/process.go
Normal file
21
component/process/process.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidNetwork = errors.New("invalid network")
|
||||||
|
ErrPlatformNotSupport = errors.New("not support on this platform")
|
||||||
|
ErrNotFound = errors.New("process not found")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
TCP = "tcp"
|
||||||
|
UDP = "udp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func FindProcessName(network string, srcIP net.IP, srcPort int) (string, error) {
|
||||||
|
return findProcessName(network, srcIP, srcPort)
|
||||||
|
}
|
104
component/process/process_darwin.go
Normal file
104
component/process/process_darwin.go
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"net"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
procpidpathinfo = 0xb
|
||||||
|
procpidpathinfosize = 1024
|
||||||
|
proccallnumpidinfo = 0x2
|
||||||
|
)
|
||||||
|
|
||||||
|
func findProcessName(network string, ip net.IP, port int) (string, error) {
|
||||||
|
var spath string
|
||||||
|
switch network {
|
||||||
|
case TCP:
|
||||||
|
spath = "net.inet.tcp.pcblist_n"
|
||||||
|
case UDP:
|
||||||
|
spath = "net.inet.udp.pcblist_n"
|
||||||
|
default:
|
||||||
|
return "", ErrInvalidNetwork
|
||||||
|
}
|
||||||
|
|
||||||
|
isIPv4 := ip.To4() != nil
|
||||||
|
|
||||||
|
value, err := syscall.Sysctl(spath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := []byte(value)
|
||||||
|
|
||||||
|
// from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n
|
||||||
|
// size/offset are round up (aligned) to 8 bytes in darwin
|
||||||
|
// rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) +
|
||||||
|
// 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n))
|
||||||
|
itemSize := 384
|
||||||
|
if network == TCP {
|
||||||
|
// rup8(sizeof(xtcpcb_n))
|
||||||
|
itemSize += 208
|
||||||
|
}
|
||||||
|
// skip the first xinpgen(24 bytes) block
|
||||||
|
for i := 24; i+itemSize <= len(buf); i += itemSize {
|
||||||
|
// offset of xinpcb_n and xsocket_n
|
||||||
|
inp, so := i, i+104
|
||||||
|
|
||||||
|
srcPort := binary.BigEndian.Uint16(buf[inp+18 : inp+20])
|
||||||
|
if uint16(port) != srcPort {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// xinpcb_n.inp_vflag
|
||||||
|
flag := buf[inp+44]
|
||||||
|
|
||||||
|
var srcIP net.IP
|
||||||
|
switch {
|
||||||
|
case flag&0x1 > 0 && isIPv4:
|
||||||
|
// ipv4
|
||||||
|
srcIP = net.IP(buf[inp+76 : inp+80])
|
||||||
|
case flag&0x2 > 0 && !isIPv4:
|
||||||
|
// ipv6
|
||||||
|
srcIP = net.IP(buf[inp+64 : inp+80])
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ip.Equal(srcIP) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// xsocket_n.so_last_pid
|
||||||
|
pid := readNativeUint32(buf[so+68 : so+72])
|
||||||
|
return getExecPathFromPID(pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
buf := make([]byte, procpidpathinfosize)
|
||||||
|
_, _, errno := syscall.Syscall6(
|
||||||
|
syscall.SYS_PROC_INFO,
|
||||||
|
proccallnumpidinfo,
|
||||||
|
uintptr(pid),
|
||||||
|
procpidpathinfo,
|
||||||
|
0,
|
||||||
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
|
procpidpathinfosize)
|
||||||
|
if errno != 0 {
|
||||||
|
return "", errno
|
||||||
|
}
|
||||||
|
|
||||||
|
return filepath.Base(unix.ByteSliceToString(buf)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readNativeUint32(b []byte) uint32 {
|
||||||
|
return *(*uint32)(unsafe.Pointer(&b[0]))
|
||||||
|
}
|
234
component/process/process_freebsd_amd64.go
Normal file
234
component/process/process_freebsd_amd64.go
Normal file
@ -0,0 +1,234 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// store process name for when dealing with multiple PROCESS-NAME rules
|
||||||
|
var (
|
||||||
|
defaultSearcher *searcher
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||||
|
once.Do(func() {
|
||||||
|
if err := initSearcher(); err != nil {
|
||||||
|
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||||
|
log.Warnln("All PROCESS-NAME rules will be skipped")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if defaultSearcher == nil {
|
||||||
|
return "", ErrPlatformNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
var spath string
|
||||||
|
isTCP := network == TCP
|
||||||
|
switch network {
|
||||||
|
case TCP:
|
||||||
|
spath = "net.inet.tcp.pcblist"
|
||||||
|
case UDP:
|
||||||
|
spath = "net.inet.udp.pcblist"
|
||||||
|
default:
|
||||||
|
return "", ErrInvalidNetwork
|
||||||
|
}
|
||||||
|
|
||||||
|
value, err := syscall.Sysctl(spath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := []byte(value)
|
||||||
|
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return getExecPathFromPID(pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
buf := make([]byte, 2048)
|
||||||
|
size := uint64(len(buf))
|
||||||
|
// CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, pid
|
||||||
|
mib := [4]uint32{1, 14, 12, pid}
|
||||||
|
|
||||||
|
_, _, errno := syscall.Syscall6(
|
||||||
|
syscall.SYS___SYSCTL,
|
||||||
|
uintptr(unsafe.Pointer(&mib[0])),
|
||||||
|
uintptr(len(mib)),
|
||||||
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
|
uintptr(unsafe.Pointer(&size)),
|
||||||
|
0,
|
||||||
|
0)
|
||||||
|
if errno != 0 || size == 0 {
|
||||||
|
return "", errno
|
||||||
|
}
|
||||||
|
|
||||||
|
return filepath.Base(string(buf[:size-1])), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readNativeUint32(b []byte) uint32 {
|
||||||
|
return *(*uint32)(unsafe.Pointer(&b[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
type searcher struct {
|
||||||
|
// sizeof(struct xinpgen)
|
||||||
|
headSize int
|
||||||
|
// sizeof(struct xtcpcb)
|
||||||
|
tcpItemSize int
|
||||||
|
// sizeof(struct xinpcb)
|
||||||
|
udpItemSize int
|
||||||
|
udpInpOffset int
|
||||||
|
port int
|
||||||
|
ip int
|
||||||
|
vflag int
|
||||||
|
socket int
|
||||||
|
|
||||||
|
// sizeof(struct xfile)
|
||||||
|
fileItemSize int
|
||||||
|
data int
|
||||||
|
pid int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *searcher) Search(buf []byte, ip net.IP, port uint16, isTCP bool) (uint32, error) {
|
||||||
|
var itemSize int
|
||||||
|
var inpOffset int
|
||||||
|
|
||||||
|
if isTCP {
|
||||||
|
// struct xtcpcb
|
||||||
|
itemSize = s.tcpItemSize
|
||||||
|
inpOffset = 8
|
||||||
|
} else {
|
||||||
|
// struct xinpcb
|
||||||
|
itemSize = s.udpItemSize
|
||||||
|
inpOffset = s.udpInpOffset
|
||||||
|
}
|
||||||
|
|
||||||
|
isIPv4 := ip.To4() != nil
|
||||||
|
// skip the first xinpgen block
|
||||||
|
for i := s.headSize; i+itemSize <= len(buf); i += itemSize {
|
||||||
|
inp := i + inpOffset
|
||||||
|
|
||||||
|
srcPort := binary.BigEndian.Uint16(buf[inp+s.port : inp+s.port+2])
|
||||||
|
|
||||||
|
if port != srcPort {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// xinpcb.inp_vflag
|
||||||
|
flag := buf[inp+s.vflag]
|
||||||
|
|
||||||
|
var srcIP net.IP
|
||||||
|
switch {
|
||||||
|
case flag&0x1 > 0 && isIPv4:
|
||||||
|
// ipv4
|
||||||
|
srcIP = net.IP(buf[inp+s.ip : inp+s.ip+4])
|
||||||
|
case flag&0x2 > 0 && !isIPv4:
|
||||||
|
// ipv6
|
||||||
|
srcIP = net.IP(buf[inp+s.ip-12 : inp+s.ip+4])
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ip.Equal(srcIP) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// xsocket.xso_so, interpreted as big endian anyway since it's only used for comparison
|
||||||
|
socket := binary.BigEndian.Uint64(buf[inp+s.socket : inp+s.socket+8])
|
||||||
|
return s.searchSocketPid(socket)
|
||||||
|
}
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *searcher) searchSocketPid(socket uint64) (uint32, error) {
|
||||||
|
value, err := syscall.Sysctl("kern.file")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := []byte(value)
|
||||||
|
|
||||||
|
// struct xfile
|
||||||
|
itemSize := s.fileItemSize
|
||||||
|
for i := 0; i+itemSize <= len(buf); i += itemSize {
|
||||||
|
// xfile.xf_data
|
||||||
|
data := binary.BigEndian.Uint64(buf[i+s.data : i+s.data+8])
|
||||||
|
if data == socket {
|
||||||
|
// xfile.xf_pid
|
||||||
|
pid := readNativeUint32(buf[i+s.pid : i+s.pid+4])
|
||||||
|
return pid, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSearcher(major int) *searcher {
|
||||||
|
var s *searcher
|
||||||
|
switch major {
|
||||||
|
case 11:
|
||||||
|
s = &searcher{
|
||||||
|
headSize: 32,
|
||||||
|
tcpItemSize: 1304,
|
||||||
|
udpItemSize: 632,
|
||||||
|
port: 198,
|
||||||
|
ip: 228,
|
||||||
|
vflag: 116,
|
||||||
|
socket: 88,
|
||||||
|
fileItemSize: 80,
|
||||||
|
data: 56,
|
||||||
|
pid: 8,
|
||||||
|
udpInpOffset: 8,
|
||||||
|
}
|
||||||
|
case 12:
|
||||||
|
fallthrough
|
||||||
|
case 13:
|
||||||
|
s = &searcher{
|
||||||
|
headSize: 64,
|
||||||
|
tcpItemSize: 744,
|
||||||
|
udpItemSize: 400,
|
||||||
|
port: 254,
|
||||||
|
ip: 284,
|
||||||
|
vflag: 392,
|
||||||
|
socket: 16,
|
||||||
|
fileItemSize: 128,
|
||||||
|
data: 56,
|
||||||
|
pid: 8,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func initSearcher() error {
|
||||||
|
osRelease, err := syscall.Sysctl("kern.osrelease")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dot := strings.Index(osRelease, ".")
|
||||||
|
if dot != -1 {
|
||||||
|
osRelease = osRelease[:dot]
|
||||||
|
}
|
||||||
|
major, err := strconv.Atoi(osRelease)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defaultSearcher = newSearcher(major)
|
||||||
|
if defaultSearcher == nil {
|
||||||
|
return fmt.Errorf("unsupported freebsd version %d", major)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
236
component/process/process_linux.go
Normal file
236
component/process/process_linux.go
Normal file
@ -0,0 +1,236 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// from https://github.com/vishvananda/netlink/blob/bca67dfc8220b44ef582c9da4e9172bf1c9ec973/nl/nl_linux.go#L52-L62
|
||||||
|
var nativeEndian = func() binary.ByteOrder {
|
||||||
|
var x uint32 = 0x01020304
|
||||||
|
if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
|
||||||
|
return binary.BigEndian
|
||||||
|
}
|
||||||
|
|
||||||
|
return binary.LittleEndian
|
||||||
|
}()
|
||||||
|
|
||||||
|
type SocketResolver func(network string, ip net.IP, srcPort int) (inode, uid int, err error)
|
||||||
|
type ProcessNameResolver func(inode, uid int) (name string, err error)
|
||||||
|
|
||||||
|
// export for android
|
||||||
|
var (
|
||||||
|
DefaultSocketResolver SocketResolver = resolveSocketByNetlink
|
||||||
|
DefaultProcessNameResolver ProcessNameResolver = resolveProcessNameByProcSearch
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48
|
||||||
|
socketDiagByFamily = 20
|
||||||
|
pathProc = "/proc"
|
||||||
|
)
|
||||||
|
|
||||||
|
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||||
|
inode, uid, err := DefaultSocketResolver(network, ip, srcPort)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return DefaultProcessNameResolver(inode, uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, error) {
|
||||||
|
var family byte
|
||||||
|
var protocol byte
|
||||||
|
|
||||||
|
switch network {
|
||||||
|
case TCP:
|
||||||
|
protocol = syscall.IPPROTO_TCP
|
||||||
|
case UDP:
|
||||||
|
protocol = syscall.IPPROTO_UDP
|
||||||
|
default:
|
||||||
|
return 0, 0, ErrInvalidNetwork
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip.To4() != nil {
|
||||||
|
family = syscall.AF_INET
|
||||||
|
} else {
|
||||||
|
family = syscall.AF_INET6
|
||||||
|
}
|
||||||
|
|
||||||
|
req := packSocketDiagRequest(family, protocol, ip, uint16(srcPort))
|
||||||
|
|
||||||
|
socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
defer syscall.Close(socket)
|
||||||
|
|
||||||
|
syscall.SetNonblock(socket, true)
|
||||||
|
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 50})
|
||||||
|
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 50})
|
||||||
|
|
||||||
|
if err := syscall.Connect(socket, &syscall.SockaddrNetlink{
|
||||||
|
Family: syscall.AF_NETLINK,
|
||||||
|
Pad: 0,
|
||||||
|
Pid: 0,
|
||||||
|
Groups: 0,
|
||||||
|
}); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := syscall.Write(socket, req); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rb := pool.Get(pool.RelayBufferSize)
|
||||||
|
defer pool.Put(rb)
|
||||||
|
|
||||||
|
n, err := syscall.Read(socket, rb)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
messages, err := syscall.ParseNetlinkMessage(rb[:n])
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
} else if len(messages) == 0 {
|
||||||
|
return 0, 0, io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
|
||||||
|
message := messages[0]
|
||||||
|
if message.Header.Type&syscall.NLMSG_ERROR != 0 {
|
||||||
|
return 0, 0, syscall.ESRCH
|
||||||
|
}
|
||||||
|
|
||||||
|
uid, inode := unpackSocketDiagResponse(&messages[0])
|
||||||
|
|
||||||
|
return int(uid), int(inode), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func packSocketDiagRequest(family, protocol byte, source net.IP, sourcePort uint16) []byte {
|
||||||
|
s := make([]byte, 16)
|
||||||
|
|
||||||
|
if v4 := source.To4(); v4 != nil {
|
||||||
|
copy(s, v4)
|
||||||
|
} else {
|
||||||
|
copy(s, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := make([]byte, sizeOfSocketDiagRequest)
|
||||||
|
|
||||||
|
nativeEndian.PutUint32(buf[0:4], sizeOfSocketDiagRequest)
|
||||||
|
nativeEndian.PutUint16(buf[4:6], socketDiagByFamily)
|
||||||
|
nativeEndian.PutUint16(buf[6:8], syscall.NLM_F_REQUEST|syscall.NLM_F_DUMP)
|
||||||
|
nativeEndian.PutUint32(buf[8:12], 0)
|
||||||
|
nativeEndian.PutUint32(buf[12:16], 0)
|
||||||
|
|
||||||
|
buf[16] = family
|
||||||
|
buf[17] = protocol
|
||||||
|
buf[18] = 0
|
||||||
|
buf[19] = 0
|
||||||
|
nativeEndian.PutUint32(buf[20:24], 0xFFFFFFFF)
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint16(buf[24:26], sourcePort)
|
||||||
|
binary.BigEndian.PutUint16(buf[26:28], 0)
|
||||||
|
|
||||||
|
copy(buf[28:44], s)
|
||||||
|
copy(buf[44:60], net.IPv6zero)
|
||||||
|
|
||||||
|
nativeEndian.PutUint32(buf[60:64], 0)
|
||||||
|
nativeEndian.PutUint64(buf[64:72], 0xFFFFFFFFFFFFFFFF)
|
||||||
|
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid uint32) {
|
||||||
|
if len(msg.Data) < 72 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
data := msg.Data
|
||||||
|
|
||||||
|
uid = nativeEndian.Uint32(data[64:68])
|
||||||
|
inode = nativeEndian.Uint32(data[68:72])
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveProcessNameByProcSearch(inode, uid int) (string, error) {
|
||||||
|
files, err := ioutil.ReadDir(pathProc)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer := make([]byte, syscall.PathMax)
|
||||||
|
socket := []byte(fmt.Sprintf("socket:[%d]", inode))
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
if !f.IsDir() || !isPid(f.Name()) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.Sys().(*syscall.Stat_t).Uid != uint32(uid) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
processPath := path.Join(pathProc, f.Name())
|
||||||
|
fdPath := path.Join(processPath, "fd")
|
||||||
|
|
||||||
|
fds, err := ioutil.ReadDir(fdPath)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, fd := range fds {
|
||||||
|
n, err := syscall.Readlink(path.Join(fdPath, fd.Name()), buffer)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if bytes.Equal(buffer[:n], socket) {
|
||||||
|
cmdline, err := ioutil.ReadFile(path.Join(processPath, "cmdline"))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return splitCmdline(cmdline), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", syscall.ESRCH
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitCmdline(cmdline []byte) string {
|
||||||
|
indexOfEndOfString := len(cmdline)
|
||||||
|
|
||||||
|
for i, c := range cmdline {
|
||||||
|
if c == 0 {
|
||||||
|
indexOfEndOfString = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filepath.Base(string(cmdline[:indexOfEndOfString]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPid(s string) bool {
|
||||||
|
for _, s := range s {
|
||||||
|
if s < '0' || s > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
13
component/process/process_other.go
Normal file
13
component/process/process_other.go
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
//go:build !darwin && !linux && !windows && (!freebsd || !amd64)
|
||||||
|
// +build !darwin
|
||||||
|
// +build !linux
|
||||||
|
// +build !windows
|
||||||
|
// +build !freebsd !amd64
|
||||||
|
|
||||||
|
package process
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||||
|
return "", ErrPlatformNotSupport
|
||||||
|
}
|
224
component/process/process_windows.go
Normal file
224
component/process/process_windows.go
Normal file
@ -0,0 +1,224 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
tcpTableFunc = "GetExtendedTcpTable"
|
||||||
|
tcpTablePidConn = 4
|
||||||
|
udpTableFunc = "GetExtendedUdpTable"
|
||||||
|
udpTablePid = 1
|
||||||
|
queryProcNameFunc = "QueryFullProcessImageNameW"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
getExTCPTable uintptr
|
||||||
|
getExUDPTable uintptr
|
||||||
|
queryProcName uintptr
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
func initWin32API() error {
|
||||||
|
h, err := windows.LoadLibrary("iphlpapi.dll")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("LoadLibrary iphlpapi.dll failed: %s", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
getExTCPTable, err = windows.GetProcAddress(h, tcpTableFunc)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("GetProcAddress of %s failed: %s", tcpTableFunc, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
getExUDPTable, err = windows.GetProcAddress(h, udpTableFunc)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("GetProcAddress of %s failed: %s", udpTableFunc, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
h, err = windows.LoadLibrary("kernel32.dll")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("LoadLibrary kernel32.dll failed: %s", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
queryProcName, err = windows.GetProcAddress(h, queryProcNameFunc)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("GetProcAddress of %s failed: %s", queryProcNameFunc, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||||
|
once.Do(func() {
|
||||||
|
err := initWin32API()
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||||
|
log.Warnln("All PROCESS-NAMES rules will be skiped")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
family := windows.AF_INET
|
||||||
|
if ip.To4() == nil {
|
||||||
|
family = windows.AF_INET6
|
||||||
|
}
|
||||||
|
|
||||||
|
var class int
|
||||||
|
var fn uintptr
|
||||||
|
switch network {
|
||||||
|
case TCP:
|
||||||
|
fn = getExTCPTable
|
||||||
|
class = tcpTablePidConn
|
||||||
|
case UDP:
|
||||||
|
fn = getExUDPTable
|
||||||
|
class = udpTablePid
|
||||||
|
default:
|
||||||
|
return "", ErrInvalidNetwork
|
||||||
|
}
|
||||||
|
|
||||||
|
buf, err := getTransportTable(fn, family, class)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
s := newSearcher(family == windows.AF_INET, network == TCP)
|
||||||
|
|
||||||
|
pid, err := s.Search(buf, ip, uint16(srcPort))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return getExecPathFromPID(pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
type searcher struct {
|
||||||
|
itemSize int
|
||||||
|
port int
|
||||||
|
ip int
|
||||||
|
ipSize int
|
||||||
|
pid int
|
||||||
|
tcpState int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *searcher) Search(b []byte, ip net.IP, port uint16) (uint32, error) {
|
||||||
|
n := int(readNativeUint32(b[:4]))
|
||||||
|
itemSize := s.itemSize
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
row := b[4+itemSize*i : 4+itemSize*(i+1)]
|
||||||
|
|
||||||
|
if s.tcpState >= 0 {
|
||||||
|
tcpState := readNativeUint32(row[s.tcpState : s.tcpState+4])
|
||||||
|
// MIB_TCP_STATE_ESTAB, only check established connections for TCP
|
||||||
|
if tcpState != 5 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// according to MSDN, only the lower 16 bits of dwLocalPort are used and the port number is in network endian.
|
||||||
|
// this field can be illustrated as follows depends on different machine endianess:
|
||||||
|
// little endian: [ MSB LSB 0 0 ] interpret as native uint32 is ((LSB<<8)|MSB)
|
||||||
|
// big endian: [ 0 0 MSB LSB ] interpret as native uint32 is ((MSB<<8)|LSB)
|
||||||
|
// so we need an syscall.Ntohs on the lower 16 bits after read the port as native uint32
|
||||||
|
srcPort := syscall.Ntohs(uint16(readNativeUint32(row[s.port : s.port+4])))
|
||||||
|
if srcPort != port {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
srcIP := net.IP(row[s.ip : s.ip+s.ipSize])
|
||||||
|
// windows binds an unbound udp socket to 0.0.0.0/[::] while first sendto
|
||||||
|
if !ip.Equal(srcIP) && (!srcIP.IsUnspecified() || s.tcpState != -1) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
pid := readNativeUint32(row[s.pid : s.pid+4])
|
||||||
|
return pid, nil
|
||||||
|
}
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSearcher(isV4, isTCP bool) *searcher {
|
||||||
|
var itemSize, port, ip, ipSize, pid int
|
||||||
|
tcpState := -1
|
||||||
|
switch {
|
||||||
|
case isV4 && isTCP:
|
||||||
|
// struct MIB_TCPROW_OWNER_PID
|
||||||
|
itemSize, port, ip, ipSize, pid, tcpState = 24, 8, 4, 4, 20, 0
|
||||||
|
case isV4 && !isTCP:
|
||||||
|
// struct MIB_UDPROW_OWNER_PID
|
||||||
|
itemSize, port, ip, ipSize, pid = 12, 4, 0, 4, 8
|
||||||
|
case !isV4 && isTCP:
|
||||||
|
// struct MIB_TCP6ROW_OWNER_PID
|
||||||
|
itemSize, port, ip, ipSize, pid, tcpState = 56, 20, 0, 16, 52, 48
|
||||||
|
case !isV4 && !isTCP:
|
||||||
|
// struct MIB_UDP6ROW_OWNER_PID
|
||||||
|
itemSize, port, ip, ipSize, pid = 28, 20, 0, 16, 24
|
||||||
|
}
|
||||||
|
|
||||||
|
return &searcher{
|
||||||
|
itemSize: itemSize,
|
||||||
|
port: port,
|
||||||
|
ip: ip,
|
||||||
|
ipSize: ipSize,
|
||||||
|
pid: pid,
|
||||||
|
tcpState: tcpState,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTransportTable(fn uintptr, family int, class int) ([]byte, error) {
|
||||||
|
for size, buf := uint32(8), make([]byte, 8); ; {
|
||||||
|
ptr := unsafe.Pointer(&buf[0])
|
||||||
|
err, _, _ := syscall.Syscall6(fn, 6, uintptr(ptr), uintptr(unsafe.Pointer(&size)), 0, uintptr(family), uintptr(class), 0)
|
||||||
|
|
||||||
|
switch err {
|
||||||
|
case 0:
|
||||||
|
return buf, nil
|
||||||
|
case uintptr(syscall.ERROR_INSUFFICIENT_BUFFER):
|
||||||
|
buf = make([]byte, size)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("syscall error: %d", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readNativeUint32(b []byte) uint32 {
|
||||||
|
return *(*uint32)(unsafe.Pointer(&b[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
// kernel process starts with a colon in order to distinguish with normal processes
|
||||||
|
switch pid {
|
||||||
|
case 0:
|
||||||
|
// reserved pid for system idle process
|
||||||
|
return ":System Idle Process", nil
|
||||||
|
case 4:
|
||||||
|
// reserved pid for windows kernel image
|
||||||
|
return ":System", nil
|
||||||
|
}
|
||||||
|
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer windows.CloseHandle(h)
|
||||||
|
|
||||||
|
buf := make([]uint16, syscall.MAX_LONG_PATH)
|
||||||
|
size := uint32(len(buf))
|
||||||
|
r1, _, err := syscall.Syscall6(
|
||||||
|
queryProcName, 4,
|
||||||
|
uintptr(h),
|
||||||
|
uintptr(1),
|
||||||
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
|
uintptr(unsafe.Pointer(&size)),
|
||||||
|
0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Base(syscall.UTF16ToString(buf[:size])), nil
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user