Compare commits
177 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
c7e34bdc11 | ||
![]() |
24186a488a | ||
![]() |
5212aaf445 | ||
![]() |
e26bed43de | ||
![]() |
700ceed194 | ||
![]() |
154cb1d1f0 | ||
![]() |
295b0da0e5 | ||
![]() |
31fe77ee69 | ||
![]() |
9177645a89 | ||
![]() |
355eb491ad | ||
![]() |
18c666a1ab | ||
![]() |
13d9e960f7 | ||
![]() |
289025c6ee | ||
![]() |
369f2735a0 | ||
![]() |
2b6dd2a909 | ||
![]() |
ccd6d321cd | ||
![]() |
4d66da2277 | ||
![]() |
1ab615852e | ||
![]() |
46bb6c38ff | ||
![]() |
c244229ffb | ||
![]() |
e8b2d0ecc8 | ||
![]() |
acec0f5c89 | ||
![]() |
4655bd4da8 | ||
![]() |
6b17fd2595 | ||
![]() |
cbcbd0e085 | ||
![]() |
75c0254703 | ||
![]() |
e02d556bf4 | ||
![]() |
d006b0f2b4 | ||
![]() |
d9753efe23 | ||
![]() |
6ecd96e5ac | ||
![]() |
fdb1456c69 | ||
![]() |
7d9723662c | ||
![]() |
ca42ca2ca8 | ||
![]() |
10dcb7a3ad | ||
![]() |
4c3c64a34a | ||
![]() |
257fcef0b8 | ||
![]() |
7f1b50f4a7 | ||
![]() |
4f5e74dad9 | ||
![]() |
48b77b2847 | ||
![]() |
6eee226965 | ||
![]() |
765982e86a | ||
![]() |
c5fe5235f7 | ||
![]() |
63770b328f | ||
![]() |
85f4cb23fc | ||
![]() |
d71324069d | ||
![]() |
b7aade5e11 | ||
![]() |
df61a586c9 | ||
![]() |
8e05fbfd6d | ||
![]() |
9b2b7c662d | ||
![]() |
20a521f02d | ||
![]() |
95bbfe3945 | ||
![]() |
4cd4912749 | ||
![]() |
5045ca4574 | ||
![]() |
a7252a1576 | ||
![]() |
7e2974f02f | ||
![]() |
8f9b39c62e | ||
![]() |
d808576f98 | ||
![]() |
fcbe2f06cc | ||
![]() |
148ebccb60 | ||
![]() |
3b1d319820 | ||
![]() |
ff2f2b667b | ||
![]() |
e5a2dbd9b5 | ||
![]() |
4d14dd65fa | ||
![]() |
4ffc999617 | ||
![]() |
71f8f0667f | ||
![]() |
f78a7cb2cb | ||
![]() |
8173d6681b | ||
![]() |
fbf2f26516 | ||
![]() |
9af6d498e7 | ||
![]() |
81b1e9f931 | ||
![]() |
58732ee8b1 | ||
![]() |
d16727e2bd | ||
![]() |
876653ebc8 | ||
![]() |
a26b670420 | ||
![]() |
0489a7391b | ||
![]() |
0c0d18a01c | ||
![]() |
e1fa343088 | ||
![]() |
a5d54884e0 | ||
![]() |
2301b909d2 | ||
![]() |
fbca37c42b | ||
![]() |
4a57917783 | ||
![]() |
cdc7d449a6 | ||
![]() |
d8ac82be36 | ||
![]() |
a6c144038b | ||
![]() |
90b40a8e5a | ||
![]() |
ed988dcdc5 | ||
![]() |
efa4b9e0b8 | ||
![]() |
8c6e205c5a | ||
![]() |
5b07d7b776 | ||
![]() |
de264c42a8 | ||
![]() |
c2469162fb | ||
![]() |
19b7c7f52a | ||
![]() |
c8bc11d61d | ||
![]() |
f29b54898f | ||
![]() |
3e2b08f9d0 | ||
![]() |
fb85691fb9 | ||
![]() |
d411394482 | ||
![]() |
827d5289bc | ||
![]() |
6995e98181 | ||
![]() |
4f291fa513 | ||
![]() |
22b9befbda | ||
![]() |
425b6e0dc0 | ||
![]() |
2516169f61 | ||
![]() |
a3281712e2 | ||
![]() |
bf079742cb | ||
![]() |
6e058f8581 | ||
![]() |
3946d771e5 | ||
![]() |
5940f62794 | ||
![]() |
71cad51e8f | ||
![]() |
50105f0559 | ||
![]() |
6648793e40 | ||
![]() |
95e3a88608 | ||
![]() |
bec4df7b12 | ||
![]() |
93400cf44d | ||
![]() |
a794819869 | ||
![]() |
be8d63ba8f | ||
![]() |
3b90e18047 | ||
![]() |
f0952b55d0 | ||
![]() |
8c7c8f4374 | ||
![]() |
65a8e8f59c | ||
![]() |
5497adaba1 | ||
![]() |
aaf08dadff | ||
![]() |
557297ac9a | ||
![]() |
77a1e3a653 | ||
![]() |
27e1d6cdae | ||
![]() |
91c22b16bf | ||
![]() |
fc5c9b931b | ||
![]() |
c231fd1466 | ||
![]() |
fbb27b84d1 | ||
![]() |
e0c5a85314 | ||
![]() |
2fa1a5c4b9 | ||
![]() |
06d75da257 | ||
![]() |
09d49bac95 | ||
![]() |
3360839fe3 | ||
![]() |
c1285adbf8 | ||
![]() |
9d2fc976e2 | ||
![]() |
7f41f94fff | ||
![]() |
d1f0dac302 | ||
![]() |
afb3e00067 | ||
![]() |
9a31ad6151 | ||
![]() |
09cc6b69e3 | ||
![]() |
8603ac40a1 | ||
![]() |
b384449717 | ||
![]() |
da7ffc0da9 | ||
![]() |
5dd94c8298 | ||
![]() |
412b44a981 | ||
![]() |
aef4dd3fe7 | ||
![]() |
6a92c6af4e | ||
![]() |
e010940b61 | ||
![]() |
2c9a4d276a | ||
![]() |
4dfba73e5c | ||
![]() |
c282d662ca | ||
![]() |
b3d7594813 | ||
![]() |
dd9bdf4e2f | ||
![]() |
275cc7edf3 | ||
![]() |
8c9e0b3884 | ||
![]() |
30d4668008 | ||
![]() |
02333a859a | ||
![]() |
f9cc1cc363 | ||
![]() |
fb7d340233 | ||
![]() |
6a661bff0c | ||
![]() |
d1dd21417b | ||
![]() |
b866f06414 | ||
![]() |
9683c297a7 | ||
![]() |
f6c7281bb7 | ||
![]() |
83bfe521b1 | ||
![]() |
b52d0c16e9 | ||
![]() |
132a6a6a2f | ||
![]() |
03e4b5d525 | ||
![]() |
a0221bf897 | ||
![]() |
b1a639feae | ||
![]() |
cfe7354c07 | ||
![]() |
9732efe938 | ||
![]() |
8f3385bbb6 | ||
![]() |
d237b041b3 | ||
![]() |
3cb87e083c | ||
![]() |
8c6d0c6757 |
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,76 +0,0 @@
|
|||||||
name: Bug report
|
|
||||||
description: Create a report to help us improve
|
|
||||||
title: "[Bug] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
如果你可以自己 debug 并解决的话,提交 PR 吧
|
|
||||||
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
|
||||||
I have searched on the [issue tracker](……/) for a related issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经使用 dev 分支版本测试过,问题依旧存在
|
|
||||||
I have tested using the dev branch, and the issue still exists.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
|
||||||
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
attributes:
|
|
||||||
label: Clash version
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: os
|
|
||||||
attributes:
|
|
||||||
label: What OS are you seeing the problem on?
|
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- macOS
|
|
||||||
- Windows
|
|
||||||
- Linux
|
|
||||||
- OpenBSD/FreeBSD
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: yaml
|
|
||||||
label: "Clash config"
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash core 脱敏后配置文件的内容
|
|
||||||
Paste the Clash core configuration below.
|
|
||||||
"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: shell
|
|
||||||
label: Clash log
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
|
||||||
"
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
validations:
|
|
||||||
required: true
|
|
124
.github/ISSUE_TEMPLATE/bug_report_en.yml
vendored
Normal file
124
.github/ISSUE_TEMPLATE/bug_report_en.yml
vendored
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
name: (English) Report a bug of the Clash core
|
||||||
|
description: Create a bug report to help us improve
|
||||||
|
labels:
|
||||||
|
- bug
|
||||||
|
title: "[Bug] <issue title>"
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## Welcome to the official Clash open-source community"
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thank you for taking the time to report an issue with the Clash core.
|
||||||
|
|
||||||
|
Prior to submitting this issue, please read and follow the guidelines below to ensure that your issue can be resolved as quickly as possible. Options marked with an asterisk (*) are required, while others are optional. If the information you provide does not comply with the requirements, the maintainers may not respond and may directly close the issue.
|
||||||
|
|
||||||
|
If you can debug and fix the issue yourself, we welcome you to submit a pull request to merge your changes upstream.
|
||||||
|
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Prerequisites
|
||||||
|
description: "If any of the following options do not apply, please do not submit this issue as we will close it"
|
||||||
|
options:
|
||||||
|
- label: "I understand that this is the official open-source version of the Clash core, **only providing support for the open-source version or Premium version**"
|
||||||
|
required: true
|
||||||
|
- label: "I am submitting an issue with the Clash core, not Clash.Meta / OpenClash / ClashX / Clash For Windows or any other derivative version"
|
||||||
|
required: true
|
||||||
|
- label: "I am using the latest version of the Clash or Clash Premium core **in this repository**"
|
||||||
|
required: true
|
||||||
|
- label: "I have searched at the [Issue Tracker](……/) **and have not found any related issues**"
|
||||||
|
required: true
|
||||||
|
- label: "I have read the [official Wiki](https://dreamacro.github.io/clash/) **and was unable to solve the issue**"
|
||||||
|
required: true
|
||||||
|
- label: "(required for Premium core) I've tried the `dev` branch and the issue still exists"
|
||||||
|
required: false
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## Environment"
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Please provide the following information to help us locate the issue.
|
||||||
|
The issue might be closed if there's not enough information provided.
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
attributes:
|
||||||
|
label: Version
|
||||||
|
description: "Run `clash -v` or look at the bottom-left corner of the Clash Dashboard to find out"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: Operating System
|
||||||
|
description: "Select all operating systems that apply to this issue"
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- Linux
|
||||||
|
- Windows
|
||||||
|
- macOS (darwin)
|
||||||
|
- Android
|
||||||
|
- OpenBSD / FreeBSD
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: arch
|
||||||
|
attributes:
|
||||||
|
label: Architecture
|
||||||
|
description: "Select all architectures that apply to this issue"
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- amd64
|
||||||
|
- amd64-v3
|
||||||
|
- arm64
|
||||||
|
- "386"
|
||||||
|
- armv5
|
||||||
|
- armv6
|
||||||
|
- armv7
|
||||||
|
- mips-softfloat
|
||||||
|
- mips-hardfloat
|
||||||
|
- mipsle-softfloat
|
||||||
|
- mipsle-hardfloat
|
||||||
|
- mips64
|
||||||
|
- mips64le
|
||||||
|
- riscv64
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## Clash related information"
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Please provide relevant information about your Clash instance here. If you
|
||||||
|
do not provide enough information, the issue may be closed.
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: YAML
|
||||||
|
label: Configuration File
|
||||||
|
placeholder: "Ensure that there is no sensitive information (such as server addresses, passwords, or ports) in the configuration file, and provide the minimum reproducible configuration. Do not post configurations with thousands of lines."
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: Text
|
||||||
|
label: Log
|
||||||
|
placeholder: "Please attach the corresponding core outout (setting `log-level: debug` in the configuration provides debugging information)."
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
placeholder: "Please describe your issue in detail here to help us understand (supports Markdown syntax)."
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Reproduction Steps
|
||||||
|
placeholder: "Please provide the specific steps to reproduce the issue here (supports Markdown syntax)."
|
||||||
|
|
121
.github/ISSUE_TEMPLATE/bug_report_zh.yml
vendored
Normal file
121
.github/ISSUE_TEMPLATE/bug_report_zh.yml
vendored
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
name: (中文)提交 Clash 核心的问题
|
||||||
|
description: 如果 Clash 核心运作不符合预期,在这里提交问题
|
||||||
|
labels:
|
||||||
|
- bug
|
||||||
|
title: "[Bug] <问题标题>"
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## 欢迎来到 Clash 官方开源社区!"
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
感谢你拨冗提交 Clash 内核的问题。在提交之前,请仔细阅读并遵守以下指引,以确保你的问题能够被尽快解决。
|
||||||
|
带有星号(*)的选项为必填,其他可选填。**如果你填写的资料不符合规范,维护者可能不予回复,并直接关闭这个 issue。**
|
||||||
|
如果你可以自行 debug 并且修正,我们随时欢迎你提交 Pull Request,将你的修改合并到上游。
|
||||||
|
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: 先决条件
|
||||||
|
description: "若以下任意选项不适用,请勿提交这个 issue,因为我们会把它关闭"
|
||||||
|
options:
|
||||||
|
- label: "我了解这里是官方开源版 Clash 核心仓库,**只提供开源版或者 Premium 内核的支持**"
|
||||||
|
required: true
|
||||||
|
- label: "我要提交 Clash 核心的问题,并非 Clash.Meta / OpenClash / ClashX / Clash For Windows 或其他任何衍生版本的问题"
|
||||||
|
required: true
|
||||||
|
- label: "我使用的是**本仓库**最新版本的 Clash 或 Clash Premium 内核"
|
||||||
|
required: true
|
||||||
|
- label: "我已经在 [Issue Tracker](……/) 中找过我要提出的 bug,**并且没有找到相关问题**"
|
||||||
|
required: true
|
||||||
|
- label: "我已经仔细阅读 [官方 Wiki](https://dreamacro.github.io/clash/) 并无法自行解决问题"
|
||||||
|
required: true
|
||||||
|
- label: "(非 Premium 内核必填)我已经使用 dev 分支版本测试过,问题依旧存在"
|
||||||
|
required: false
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## 系统环境"
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
请附上这个问题适用的环境,以帮助我们迅速定位问题并解决。若你提供的信息不足,我们将关闭
|
||||||
|
这个 issue 并要求你提供更多信息。
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
attributes:
|
||||||
|
label: 版本
|
||||||
|
description: "运行 `clash -v` 或者查看 Clash Dashboard 的左下角来找到你现在使用的版本"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: 适用的作业系统
|
||||||
|
description: "勾选所有适用于这个 issue 的系统"
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- Linux
|
||||||
|
- Windows
|
||||||
|
- macOS (darwin)
|
||||||
|
- Android
|
||||||
|
- OpenBSD / FreeBSD
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: arch
|
||||||
|
attributes:
|
||||||
|
label: 适用的硬件架构
|
||||||
|
description: "勾选所有适用于这个 issue 的架构"
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- amd64
|
||||||
|
- amd64-v3
|
||||||
|
- arm64
|
||||||
|
- "386"
|
||||||
|
- armv5
|
||||||
|
- armv6
|
||||||
|
- armv7
|
||||||
|
- mips-softfloat
|
||||||
|
- mips-hardfloat
|
||||||
|
- mipsle-softfloat
|
||||||
|
- mipsle-hardfloat
|
||||||
|
- mips64
|
||||||
|
- mips64le
|
||||||
|
- riscv64
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## Clash 相关信息"
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
请附上与这个问题直接相关的相应信息,以帮助我们迅速定位问题并解决。
|
||||||
|
若你提供的信息不足,我们将关闭这个 issue 并要求你提供更多信息。
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: YAML
|
||||||
|
label: "配置文件"
|
||||||
|
placeholder: "确保配置文件中没有敏感信息(如:服务器地址、密码、端口),并且提供最小可复现配置,严禁贴上上千行的配置"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: Text
|
||||||
|
label: 日志输出
|
||||||
|
placeholder: "在这里附上问题对应的内核日志(在配置中设置 `log-level: debug` 可获得调试信息)"
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 问题描述
|
||||||
|
placeholder: "在这里详细叙述你的问题,帮助我们理解(支持 Markdown 语法)"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 复现步骤
|
||||||
|
placeholder: "在这里提供问题的具体重现步骤(支持 Markdown 语法)"
|
9
.github/ISSUE_TEMPLATE/config.yml
vendored
9
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -1,6 +1,9 @@
|
|||||||
blank_issues_enabled: false
|
blank_issues_enabled: false
|
||||||
|
|
||||||
contact_links:
|
contact_links:
|
||||||
- name: Get help in GitHub Discussions
|
- name: (中文)阅读 Wiki
|
||||||
url: https://github.com/Dreamacro/clash/discussions
|
url: https://dreamacro.github.io/clash/zh_CN/
|
||||||
about: Have a question? Not sure if your issue affects everyone reproducibly? The quickest way to get help is on Clash's GitHub Discussions!
|
about: 如果你是新手,或者想要了解 Clash 的更多信息,请阅读我们撰写的官方 Wiki
|
||||||
|
- name: (English) Read our Wiki page
|
||||||
|
url: https://dreamacro.github.io/clash/
|
||||||
|
about: If you are new to Clash, or want to know more about Clash, please read our Wiki page
|
||||||
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,36 +0,0 @@
|
|||||||
name: Feature request
|
|
||||||
description: Suggest an idea for this project
|
|
||||||
title: "[Feature] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
|
||||||
I have searched on the [issue tracker](……/) for a related feature request.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Possible Solution
|
|
||||||
description: "
|
|
||||||
此项非必须,但是如果你有想法的话欢迎提出。
|
|
||||||
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
|
||||||
"
|
|
43
.github/ISSUE_TEMPLATE/feature_request_en.yml
vendored
Normal file
43
.github/ISSUE_TEMPLATE/feature_request_en.yml
vendored
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
name: (English) Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
labels:
|
||||||
|
- enhancement
|
||||||
|
title: "[Feature] <title>"
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## Welcome to the official Clash open-source community"
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thank you for taking the time to make a suggestion to the Clash core.
|
||||||
|
|
||||||
|
Prior to submitting this issue, please read and follow the guidelines below to ensure that your issue can be resolved as quickly as possible. Options marked with an asterisk (*) are required, while others are optional. If the information you provide does not comply with the requirements, the maintainers may not respond and may directly close the issue.
|
||||||
|
|
||||||
|
If you can implement your idea by yourself, we welcome you to submit a pull request to merge your changes upstream.
|
||||||
|
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Prerequisites
|
||||||
|
description: "If any of the following options do not apply, please do not submit this issue as we will close it"
|
||||||
|
options:
|
||||||
|
- label: "I understand that this is the official open-source version of the Clash core, **only providing support for the open-source version or Premium version**"
|
||||||
|
required: true
|
||||||
|
- label: "I have looked for my idea in [the issue tracker](https://github.com/Dreamacro/clash/issues?q=is%3Aissue+label%3Aenhancement), **and found none of which being related**"
|
||||||
|
required: true
|
||||||
|
- label: "I have read the [official Wiki](https://dreamacro.github.io/clash/)"
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
placeholder: "Please explain your suggestions in detail and in a clear manner. For instance, how does this issue impact you? What specific functionality are you hoping to achieve? Also, let us know what Clash Core is currently doing in terms of your suggestion, and what you would like it to do instead."
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Possible Solution
|
||||||
|
placeholder: "Do you have any ideas on the implementation details?"
|
41
.github/ISSUE_TEMPLATE/feature_request_zh.yml
vendored
Normal file
41
.github/ISSUE_TEMPLATE/feature_request_zh.yml
vendored
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
name: (中文)建议一个新功能
|
||||||
|
description: 在这里提供一个的想法或建议
|
||||||
|
labels:
|
||||||
|
- enhancement
|
||||||
|
title: "[Feature] <标题>"
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: "## 欢迎来到 Clash 官方开源社区!"
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
感谢你拨冗为 Clash 内核提供建议。在提交之前,请仔细阅读并遵守以下指引,以确保你的建议能够被顺利采纳。
|
||||||
|
带有星号(*)的选项为必填,其他可选填。**如果你填写的资料不符合规范,维护者可能不予回复,并直接关闭这个 issue。**
|
||||||
|
如果你可以自行添加这个功能,我们随时欢迎你提交 Pull Request,并将你的修改合并到上游。
|
||||||
|
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: 先决条件
|
||||||
|
description: "若以下任意选项不适用,请勿提交这个 issue,因为我们会把它关闭"
|
||||||
|
options:
|
||||||
|
- label: "我了解这里是 Clash 官方仓库,并非 Clash.Meta / OpenClash / ClashX / Clash For Windows 或其他任何衍生版本"
|
||||||
|
required: true
|
||||||
|
- label: "我已经在[这里](https://github.com/Dreamacro/clash/issues?q=is%3Aissue+label%3Aenhancement)找过我要提出的建议,**并且没有找到相关问题**"
|
||||||
|
required: true
|
||||||
|
- label: "我已经仔细阅读 [官方 Wiki](https://dreamacro.github.io/clash/) "
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 描述
|
||||||
|
placeholder: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什么?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: 可能的解决方案
|
||||||
|
placeholder: 此项非必须,但是如果你有想法的话欢迎提出。
|
14
.github/workflows/codeql-analysis.yml
vendored
14
.github/workflows/codeql-analysis.yml
vendored
@ -1,8 +1,8 @@
|
|||||||
name: "CodeQL"
|
name: CodeQL
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master, dev ]
|
branches: [master, dev]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
@ -12,19 +12,19 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
language: [ 'go' ]
|
language: ['go']
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Initialize CodeQL
|
- name: Initialize CodeQL
|
||||||
uses: github/codeql-action/init@v1
|
uses: github/codeql-action/init@v2
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
|
|
||||||
- name: Autobuild
|
- name: Autobuild
|
||||||
uses: github/codeql-action/autobuild@v1
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@v1
|
uses: github/codeql-action/analyze@v2
|
||||||
|
42
.github/workflows/deploy-docs.yml
vendored
Normal file
42
.github/workflows/deploy-docs.yml
vendored
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
name: Deploy
|
||||||
|
on:
|
||||||
|
workflow_dispatch: {}
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
node-version: [20]
|
||||||
|
permissions:
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: pnpm/action-setup@v2
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
- name: Use Node.js ${{ matrix.node-version }}
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: ${{ matrix.node-version }}
|
||||||
|
- name: Install dependencies
|
||||||
|
working-directory: docs
|
||||||
|
run: pnpm install --frozen-lockfile=false
|
||||||
|
- name: Build
|
||||||
|
working-directory: docs
|
||||||
|
run: pnpm run docs:build
|
||||||
|
- uses: actions/configure-pages@v2
|
||||||
|
- uses: actions/upload-pages-artifact@v1
|
||||||
|
with:
|
||||||
|
path: docs/.vitepress/dist
|
||||||
|
- name: Deploy
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v2
|
22
.github/workflows/docker.yml
vendored
22
.github/workflows/docker.yml
vendored
@ -13,29 +13,29 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v1
|
uses: docker/setup-qemu-action@v2
|
||||||
with:
|
with:
|
||||||
platforms: all
|
platforms: all
|
||||||
|
|
||||||
- name: Set up docker buildx
|
- name: Set up docker buildx
|
||||||
id: buildx
|
id: buildx
|
||||||
uses: docker/setup-buildx-action@v1
|
uses: docker/setup-buildx-action@v2
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
- name: Login to DockerHub
|
- name: Login to DockerHub
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
- name: Login to Github Package
|
- name: Login to Github Package
|
||||||
uses: docker/login-action@v1
|
uses: docker/login-action@v2
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: Dreamacro
|
username: Dreamacro
|
||||||
@ -43,20 +43,22 @@ jobs:
|
|||||||
|
|
||||||
- name: Build dev branch and push
|
- name: Build dev branch and push
|
||||||
if: github.ref == 'refs/heads/dev'
|
if: github.ref == 'refs/heads/dev'
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
push: true
|
push: true
|
||||||
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
- name: Get all docker tags
|
- name: Get all docker tags
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
uses: actions/github-script@v4
|
uses: actions/github-script@v6
|
||||||
id: tags
|
id: tags
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
const ref = `${context.payload.ref.replace(/\/?refs\/tags\//, '')}`
|
const ref = context.payload.ref.replace(/\/?refs\/tags\//, '')
|
||||||
const tags = [
|
const tags = [
|
||||||
'dreamacro/clash:latest',
|
'dreamacro/clash:latest',
|
||||||
`dreamacro/clash:${ref}`,
|
`dreamacro/clash:${ref}`,
|
||||||
@ -68,9 +70,11 @@ jobs:
|
|||||||
|
|
||||||
- name: Build release and push
|
- name: Build release and push
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
push: true
|
push: true
|
||||||
tags: ${{steps.tags.outputs.result}}
|
tags: ${{steps.tags.outputs.result}}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
12
.github/workflows/linter.yml
vendored
12
.github/workflows/linter.yml
vendored
@ -4,9 +4,15 @@ jobs:
|
|||||||
lint:
|
lint:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
check-latest: true
|
||||||
|
go-version: '1.20'
|
||||||
|
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v3
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
args: --disable-all -E govet -E gofumpt -E megacheck ./...
|
|
||||||
|
20
.github/workflows/release.yml
vendored
20
.github/workflows/release.yml
vendored
@ -4,23 +4,21 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
check-latest: true
|
||||||
|
go-version: '1.20'
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Cache go module
|
- name: Cache go module
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: |
|
||||||
|
~/go/pkg/mod
|
||||||
|
~/.cache/go-build
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-go-
|
${{ runner.os }}-go-
|
||||||
@ -34,7 +32,7 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
NAME: clash
|
NAME: clash
|
||||||
BINDIR: bin
|
BINDIR: bin
|
||||||
run: make -j releases
|
run: make -j $(go run ./test/main.go) releases
|
||||||
|
|
||||||
- name: Upload Release
|
- name: Upload Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
|
2
.github/workflows/stale.yml
vendored
2
.github/workflows/stale.yml
vendored
@ -11,7 +11,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/stale@v4
|
- uses: actions/stale@v7
|
||||||
with:
|
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'
|
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-stale: 60
|
||||||
|
11
.gitignore
vendored
11
.gitignore
vendored
@ -23,3 +23,14 @@ vendor
|
|||||||
|
|
||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
|
|
||||||
|
# docs site generator
|
||||||
|
node_modules
|
||||||
|
package-lock.json
|
||||||
|
pnpm-lock.yaml
|
||||||
|
|
||||||
|
# docs site cache
|
||||||
|
docs/.vitepress/cache
|
||||||
|
|
||||||
|
# docs site build files
|
||||||
|
docs/.vitepress/dist
|
||||||
|
23
.golangci.yaml
Normal file
23
.golangci.yaml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- gci
|
||||||
|
- gofumpt
|
||||||
|
- gosimple
|
||||||
|
- govet
|
||||||
|
- ineffassign
|
||||||
|
- misspell
|
||||||
|
- staticcheck
|
||||||
|
- unconvert
|
||||||
|
- unused
|
||||||
|
- usestdlibvars
|
||||||
|
|
||||||
|
linters-settings:
|
||||||
|
gci:
|
||||||
|
custom-order: true
|
||||||
|
sections:
|
||||||
|
- standard
|
||||||
|
- prefix(github.com/Dreamacro/clash)
|
||||||
|
- default
|
||||||
|
staticcheck:
|
||||||
|
go: '1.20'
|
20
Dockerfile
20
Dockerfile
@ -1,18 +1,22 @@
|
|||||||
FROM golang:alpine as builder
|
FROM --platform=${BUILDPLATFORM} golang:alpine as builder
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache make git ca-certificates tzdata && \
|
||||||
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 /workdir
|
||||||
COPY --from=tonistiigi/xx:golang / /
|
COPY --from=tonistiigi/xx:golang / /
|
||||||
COPY . /clash-src
|
ARG TARGETOS TARGETARCH TARGETVARIANT
|
||||||
RUN go mod download && \
|
|
||||||
make docker && \
|
RUN --mount=target=. \
|
||||||
mv ./bin/clash-docker /clash
|
--mount=type=cache,target=/root/.cache/go-build \
|
||||||
|
--mount=type=cache,target=/go/pkg/mod \
|
||||||
|
make BINDIR= ${TARGETOS}-${TARGETARCH}${TARGETVARIANT} && \
|
||||||
|
mv /clash* /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates
|
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
|
||||||
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
COPY --from=builder /clash /
|
COPY --from=builder /clash /
|
||||||
ENTRYPOINT ["/clash"]
|
ENTRYPOINT ["/clash"]
|
||||||
|
46
Makefile
46
Makefile
@ -8,37 +8,43 @@ GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clas
|
|||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
|
darwin-amd64-v3 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-386 \
|
linux-386 \
|
||||||
linux-amd64 \
|
linux-amd64 \
|
||||||
|
linux-amd64-v3 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
linux-armv8 \
|
linux-arm64 \
|
||||||
linux-mips-softfloat \
|
linux-mips-softfloat \
|
||||||
linux-mips-hardfloat \
|
linux-mips-hardfloat \
|
||||||
linux-mipsle-softfloat \
|
linux-mipsle-softfloat \
|
||||||
linux-mipsle-hardfloat \
|
linux-mipsle-hardfloat \
|
||||||
linux-mips64 \
|
linux-mips64 \
|
||||||
linux-mips64le \
|
linux-mips64le \
|
||||||
|
linux-riscv64 \
|
||||||
|
linux-loong64 \
|
||||||
freebsd-386 \
|
freebsd-386 \
|
||||||
freebsd-amd64 \
|
freebsd-amd64 \
|
||||||
|
freebsd-amd64-v3 \
|
||||||
freebsd-arm64
|
freebsd-arm64
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-386 \
|
||||||
windows-amd64 \
|
windows-amd64 \
|
||||||
|
windows-amd64-v3 \
|
||||||
windows-arm64 \
|
windows-arm64 \
|
||||||
windows-arm32v7
|
windows-armv7
|
||||||
|
|
||||||
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-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -48,6 +54,9 @@ linux-386:
|
|||||||
linux-amd64:
|
linux-amd64:
|
||||||
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-armv5:
|
linux-armv5:
|
||||||
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -57,7 +66,7 @@ linux-armv6:
|
|||||||
linux-armv7:
|
linux-armv7:
|
||||||
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-armv8:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-mips-softfloat:
|
linux-mips-softfloat:
|
||||||
@ -78,12 +87,21 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-riscv64:
|
||||||
|
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-loong64:
|
||||||
|
GOARCH=loong64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-386:
|
freebsd-386:
|
||||||
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-amd64:
|
freebsd-amd64:
|
||||||
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-arm64:
|
freebsd-arm64:
|
||||||
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -93,10 +111,13 @@ windows-386:
|
|||||||
windows-amd64:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64-v3:
|
||||||
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm32v7:
|
windows-armv7:
|
||||||
GOARCH=arm GOOS=windows GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm GOOS=windows GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
||||||
@ -113,8 +134,15 @@ all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
|||||||
|
|
||||||
releases: $(gz_releases) $(zip_releases)
|
releases: $(gz_releases) $(zip_releases)
|
||||||
|
|
||||||
lint:
|
LINT_OS_LIST := darwin windows linux freebsd openbsd
|
||||||
golangci-lint run --disable-all -E govet -E gofumpt -E megacheck ./...
|
|
||||||
|
lint: $(foreach os,$(LINT_OS_LIST),$(os)-lint)
|
||||||
|
%-lint:
|
||||||
|
GOOS=$* golangci-lint run ./...
|
||||||
|
|
||||||
|
lint-fix: $(foreach os,$(LINT_OS_LIST),$(os)-lint-fix)
|
||||||
|
%-lint-fix:
|
||||||
|
GOOS=$* golangci-lint run --fix ./...
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm $(BINDIR)/*
|
||||||
|
39
README.md
39
README.md
@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/Dreamacro/clash/actions">
|
<a href="https://github.com/Dreamacro/clash/actions">
|
||||||
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
<img src="https://img.shields.io/github/actions/workflow/status/Dreamacro/clash/release.yml?branch=master&style=flat-square" alt="Github Actions">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||||
@ -23,35 +23,28 @@
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Local HTTP/HTTPS/SOCKS server with authentication support
|
This is a general overview of the features that comes with Clash.
|
||||||
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
|
||||||
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
|
||||||
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
|
||||||
- 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
|
|
||||||
|
|
||||||
## Premium Features
|
- Inbound: HTTP, HTTPS, SOCKS5 server, TUN device
|
||||||
|
- Outbound: Shadowsocks(R), VMess, Trojan, Snell, SOCKS5, HTTP(S), Wireguard
|
||||||
|
- Rule-based Routing: dynamic scripting, domain, IP addresses, process name and more
|
||||||
|
- Fake-IP DNS: minimises impact on DNS pollution and improves network performance
|
||||||
|
- Transparent Proxy: Redirect TCP and TProxy TCP/UDP with automatic route table/rule management
|
||||||
|
- Proxy Groups: automatic fallback, load balancing or latency testing
|
||||||
|
- Remote Providers: load remote proxy lists dynamically
|
||||||
|
- RESTful API: update configuration in-place via a comprehensive API
|
||||||
|
|
||||||
- TUN mode on macOS, Linux and Windows. [Doc](https://github.com/Dreamacro/clash/wiki/premium-core-features#tun-device)
|
*Some of the features may only be available in the [Premium core](https://dreamacro.github.io/clash/premium/introduction.html).*
|
||||||
- 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)
|
|
||||||
|
|
||||||
## Getting Started
|
## Documentation
|
||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
|
||||||
|
|
||||||
## Premium Release
|
You can find the latest documentation at [https://dreamacro.github.io/clash/](https://dreamacro.github.io/clash/).
|
||||||
[Release](https://github.com/Dreamacro/clash/releases/tag/premium)
|
|
||||||
|
|
||||||
## Development
|
|
||||||
If you want to build an application that uses clash as a library, check out the the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -91,9 +91,10 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
return inner, err
|
return inner, err
|
||||||
}
|
}
|
||||||
|
|
||||||
mapping := map[string]interface{}{}
|
mapping := map[string]any{}
|
||||||
json.Unmarshal(inner, &mapping)
|
json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
|
mapping["alive"] = p.Alive()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
@ -101,12 +102,13 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
// URLTest get the delay for the specified URL
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
func (p *Proxy) URLTest(ctx context.Context, url string) (delay, meanDelay uint16, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
p.alive.Store(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 = delay
|
||||||
|
record.MeanDelay = meanDelay
|
||||||
}
|
}
|
||||||
p.history.Put(record)
|
p.history.Put(record)
|
||||||
if p.history.Len() > 10 {
|
if p.history.Len() > 10 {
|
||||||
@ -156,7 +158,16 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
resp.Body.Close()
|
resp.Body.Close()
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
delay = uint16(time.Since(start) / time.Millisecond)
|
||||||
|
|
||||||
|
resp, err = client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
// ignore error because some server will hijack the connection and close immediately
|
||||||
|
return delay, 0, nil
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
meanDelay = uint16(time.Since(start) / time.Millisecond / 2)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -184,7 +195,6 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: u.Hostname(),
|
Host: u.Hostname(),
|
||||||
DstIP: nil,
|
DstIP: nil,
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
|
@ -2,6 +2,7 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -9,7 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnContext {
|
func NewHTTP(target socks5.Addr, source net.Addr, originTarget net.Addr, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
@ -17,5 +18,10 @@ func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnCo
|
|||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if originTarget != nil {
|
||||||
|
if addrPort, err := netip.ParseAddrPort(originTarget.String()); err == nil {
|
||||||
|
metadata.OriginDst = addrPort
|
||||||
|
}
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -16,5 +17,8 @@ func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
|||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if addrPort, err := netip.ParseAddrPort(conn.LocalAddr().String()); err == nil {
|
||||||
|
metadata.OriginDst = addrPort
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -17,7 +20,7 @@ func (s *PacketAdapter) Metadata() *C.Metadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
func NewPacket(target socks5.Addr, originTarget net.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
@ -25,7 +28,11 @@ func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAda
|
|||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if originTarget != nil {
|
||||||
|
if addrPort, err := netip.ParseAddrPort(originTarget.String()); err == nil {
|
||||||
|
metadata.OriginDst = addrPort
|
||||||
|
}
|
||||||
|
}
|
||||||
return &PacketAdapter{
|
return &PacketAdapter{
|
||||||
UDPPacket: packet,
|
UDPPacket: packet,
|
||||||
metadata: metadata,
|
metadata: metadata,
|
||||||
|
@ -2,6 +2,7 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -17,6 +18,8 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
|||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
|
if addrPort, err := netip.ParseAddrPort(conn.LocalAddr().String()); err == nil {
|
||||||
|
metadata.OriginDst = addrPort
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -11,9 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{}
|
||||||
AddrType: int(target[0]),
|
|
||||||
}
|
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -45,20 +43,12 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: nil,
|
DstIP: nil,
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
if ip != nil {
|
|
||||||
switch {
|
|
||||||
case ip.To4() == nil:
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
default:
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,6 +22,7 @@ type Http struct {
|
|||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
|
Headers http.Header
|
||||||
}
|
}
|
||||||
|
|
||||||
type HttpOption struct {
|
type HttpOption struct {
|
||||||
@ -34,13 +35,16 @@ type HttpOption struct {
|
|||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
err := cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
@ -61,7 +65,9 @@ func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = h.StreamConn(c, metadata)
|
c, err = h.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -79,11 +85,11 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
Host: addr,
|
Host: addr,
|
||||||
},
|
},
|
||||||
Host: addr,
|
Host: addr,
|
||||||
Header: http.Header{
|
Header: h.Headers.Clone(),
|
||||||
"Proxy-Connection": []string{"Keep-Alive"},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
req.Header.Add("Proxy-Connection", "Keep-Alive")
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
auth := h.user + ":" + h.pass
|
auth := h.user + ":" + h.pass
|
||||||
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
@ -130,15 +136,22 @@ func NewHttp(option HttpOption) *Http {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
headers := http.Header{}
|
||||||
|
for name, value := range option.Headers {
|
||||||
|
headers.Add(name, value)
|
||||||
|
}
|
||||||
|
|
||||||
return &Http{
|
return &Http{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
|
Headers: headers,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,11 +10,10 @@ import (
|
|||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
@ -36,7 +35,7 @@ type ShadowSocksOption struct {
|
|||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -82,7 +81,9 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
@ -160,6 +161,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
cipher: ciph,
|
cipher: ciph,
|
||||||
|
|
||||||
|
@ -8,12 +8,11 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"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 {
|
type ShadowSocksR struct {
|
||||||
@ -67,7 +66,9 @@ func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ssr.StreamConn(c, metadata)
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
@ -92,6 +93,12 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
|
// SSR protocol compatibility
|
||||||
|
// https://github.com/Dreamacro/clash/pull/2056
|
||||||
|
if option.Cipher == "none" {
|
||||||
|
option.Cipher = "dummy"
|
||||||
|
}
|
||||||
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
cipher := option.Cipher
|
cipher := option.Cipher
|
||||||
password := option.Password
|
password := option.Password
|
||||||
@ -103,13 +110,14 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
ivSize int
|
ivSize int
|
||||||
key []byte
|
key []byte
|
||||||
)
|
)
|
||||||
|
|
||||||
if option.Cipher == "dummy" {
|
if option.Cipher == "dummy" {
|
||||||
ivSize = 0
|
ivSize = 0
|
||||||
key = core.Kdf(option.Password, 16)
|
key = core.Kdf(option.Password, 16)
|
||||||
} else {
|
} else {
|
||||||
ciph, ok := coreCiph.(*core.StreamCipher)
|
ciph, ok := coreCiph.(*core.StreamCipher)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("%s is not dummy or a supported stream cipher in ssr", cipher)
|
return nil, fmt.Errorf("%s is not none or a supported stream cipher in ssr", cipher)
|
||||||
}
|
}
|
||||||
ivSize = ciph.IVSize()
|
ivSize = ciph.IVSize()
|
||||||
key = ciph.Key
|
key = ciph.Key
|
||||||
@ -142,6 +150,7 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
|
@ -27,8 +27,9 @@ type SnellOption struct {
|
|||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Psk string `proxy:"psk"`
|
Psk string `proxy:"psk"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Version int `proxy:"version,omitempty"`
|
Version int `proxy:"version,omitempty"`
|
||||||
ObfsOpts map[string]interface{} `proxy:"obfs-opts,omitempty"`
|
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type streamOption struct {
|
type streamOption struct {
|
||||||
@ -79,12 +80,32 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = s.StreamConn(c, metadata)
|
c, err = s.StreamConn(c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
psk := []byte(option.Psk)
|
psk := []byte(option.Psk)
|
||||||
@ -106,7 +127,13 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
if option.Version == 0 {
|
if option.Version == 0 {
|
||||||
option.Version = snell.DefaultSnellVersion
|
option.Version = snell.DefaultSnellVersion
|
||||||
}
|
}
|
||||||
if option.Version != snell.Version1 && option.Version != snell.Version2 {
|
switch option.Version {
|
||||||
|
case snell.Version1, snell.Version2:
|
||||||
|
if option.UDP {
|
||||||
|
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
|
||||||
|
}
|
||||||
|
case snell.Version3:
|
||||||
|
default:
|
||||||
return nil, fmt.Errorf("snell version error: %d", option.Version)
|
return nil, fmt.Errorf("snell version error: %d", option.Version)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,7 +142,9 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -39,7 +39,9 @@ type Socks5Option struct {
|
|||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err := cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@ -67,7 +69,9 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -87,11 +91,15 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err = cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err = cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
@ -154,6 +162,7 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
|||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
|
@ -109,7 +109,9 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = t.StreamConn(c, metadata)
|
c, err = t.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -129,13 +131,17 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
} else {
|
} else {
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -173,6 +179,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
instance: trojan.New(tOption),
|
||||||
option: &option,
|
option: &option,
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package outbound
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
@ -9,6 +8,8 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/protobytes"
|
||||||
)
|
)
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
@ -19,23 +20,24 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
buf := protobytes.BytesWriter{}
|
||||||
aType := uint8(metadata.AddrType)
|
|
||||||
|
addrType := metadata.AddrType()
|
||||||
|
buf.PutUint8(uint8(addrType))
|
||||||
|
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
switch addrType {
|
||||||
switch metadata.AddrType {
|
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
len := uint8(len(metadata.Host))
|
buf.PutUint8(uint8(len(metadata.Host)))
|
||||||
host := []byte(metadata.Host)
|
buf.PutString(metadata.Host)
|
||||||
buf = [][]byte{{aType, len}, host, port}
|
|
||||||
case socks5.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
host := metadata.DstIP.To4()
|
buf.PutSlice(metadata.DstIP.To4())
|
||||||
buf = [][]byte{{aType}, host, port}
|
|
||||||
case socks5.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
host := metadata.DstIP.To16()
|
buf.PutSlice(metadata.DstIP.To16())
|
||||||
buf = [][]byte{{aType}, host, port}
|
|
||||||
}
|
}
|
||||||
return bytes.Join(buf, nil)
|
|
||||||
|
buf.PutUint16be(uint16(p))
|
||||||
|
return buf.Bytes()
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||||
|
@ -14,11 +14,14 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
*Base
|
*Base
|
||||||
client *vmess.Client
|
client *vmess.Client
|
||||||
@ -192,7 +195,9 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -207,7 +212,9 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
@ -231,7 +238,9 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
} else {
|
} else {
|
||||||
@ -240,7 +249,9 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
@ -280,6 +291,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -326,17 +338,17 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType() {
|
||||||
case C.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
addrType = byte(vmess.AtypIPv4)
|
addrType = vmess.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.To4())
|
copy(addr[:], metadata.DstIP.To4())
|
||||||
case C.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
addrType = byte(vmess.AtypIPv6)
|
addrType = vmess.AtypIPv6
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.To16())
|
copy(addr[:], metadata.DstIP.To16())
|
||||||
case C.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
addrType = byte(vmess.AtypDomainName)
|
addrType = vmess.AtypDomainName
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
@ -356,7 +368,14 @@ type vmessPacketConn struct {
|
|||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteTo implments C.PacketConn.WriteTo
|
||||||
|
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
allowedAddr := uc.rAddr.(*net.UDPAddr)
|
||||||
|
destAddr := addr.(*net.UDPAddr)
|
||||||
|
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
|
||||||
|
return 0, ErrUDPRemoteAddrMismatch
|
||||||
|
}
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -11,14 +11,19 @@ const (
|
|||||||
defaultGetProxiesDuration = time.Second * 5
|
defaultGetProxiesDuration = time.Second * 5
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func touchProviders(providers []provider.ProxyProvider) {
|
||||||
|
for _, provider := range providers {
|
||||||
|
provider.Touch()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
for _, provider := range providers {
|
for _, provider := range providers {
|
||||||
if touch {
|
if touch {
|
||||||
proxies = append(proxies, provider.ProxiesWithTouch()...)
|
provider.Touch()
|
||||||
} else {
|
|
||||||
proxies = append(proxies, provider.Proxies()...)
|
|
||||||
}
|
}
|
||||||
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
}
|
}
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
@ -59,7 +59,7 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
for _, proxy := range f.proxies(false) {
|
for _, proxy := range f.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"type": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
"now": f.Now(),
|
"now": f.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
@ -73,7 +73,7 @@ func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := f.single.Do(func() (interface{}, error) {
|
elm, _, _ := f.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(f.providers, touch), nil
|
return getProvidersProxies(f.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -29,12 +29,10 @@ type LoadBalance struct {
|
|||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
func parseStrategy(config map[string]interface{}) string {
|
func parseStrategy(config map[string]any) string {
|
||||||
if elm, ok := config["strategy"]; ok {
|
if strategy, ok := config["strategy"].(string); ok {
|
||||||
if strategy, ok := elm.(string); ok {
|
|
||||||
return strategy
|
return strategy
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return "consistent-hashing"
|
return "consistent-hashing"
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,6 +127,13 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -140,7 +145,7 @@ func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := lb.single.Do(func() (interface{}, error) {
|
elm, _, _ := lb.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(lb.providers, touch), nil
|
return getProvidersProxies(lb.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -153,7 +158,7 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|||||||
for _, proxy := range lb.proxies(false) {
|
for _, proxy := range lb.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"type": lb.Type().String(),
|
"type": lb.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
})
|
})
|
||||||
|
@ -9,6 +9,8 @@ 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"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
|
regexp "github.com/dlclark/regexp2"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -16,7 +18,7 @@ var (
|
|||||||
errType = errors.New("unsupport type")
|
errType = errors.New("unsupport type")
|
||||||
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 {
|
||||||
@ -29,9 +31,10 @@ type GroupCommonOption struct {
|
|||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
|
Filter string `group:"filter,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]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{
|
||||||
@ -45,22 +48,33 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
groupName := groupOption.Name
|
var (
|
||||||
|
groupName = groupOption.Name
|
||||||
|
filterReg *regexp.Regexp
|
||||||
|
)
|
||||||
|
|
||||||
providers := []types.ProxyProvider{}
|
if groupOption.Filter != "" {
|
||||||
|
f, err := regexp.Compile(groupOption.Filter, regexp.None)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: invalid filter regex: %w", groupName, err)
|
||||||
|
}
|
||||||
|
filterReg = f
|
||||||
|
}
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
return nil, errMissProxy
|
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
if len(groupOption.Proxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := providersMap[groupName]; ok {
|
if _, ok := providersMap[groupName]; ok {
|
||||||
return nil, errDuplicateProvider
|
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
// select don't need health check
|
// select don't need health check
|
||||||
@ -68,20 +82,20 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
hc := provider.NewHealthCheck(ps, "", 0, true)
|
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, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
} else {
|
} else {
|
||||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||||
return nil, errMissHealthCheck
|
return nil, fmt.Errorf("%s: %w", groupName, errMissHealthCheck)
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
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, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
@ -92,10 +106,15 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
if len(groupOption.Use) != 0 {
|
if len(groupOption.Use) != 0 {
|
||||||
list, err := getProviders(providersMap, groupOption.Use)
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
if filterReg != nil {
|
||||||
|
pd := provider.NewFilterableProvider(groupName, list, filterReg)
|
||||||
|
providers = append(providers, pd)
|
||||||
|
} else {
|
||||||
providers = append(providers, list...)
|
providers = append(providers, list...)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
switch groupOption.Type {
|
switch groupOption.Type {
|
||||||
@ -112,7 +131,7 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy,
|
|||||||
case "relay":
|
case "relay":
|
||||||
group = NewRelay(groupOption, providers)
|
group = NewRelay(groupOption, providers)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
return nil, fmt.Errorf("%s %w: %s", groupName, errType, groupOption.Type)
|
||||||
}
|
}
|
||||||
|
|
||||||
return group, nil
|
return group, nil
|
||||||
|
@ -72,14 +72,14 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
for _, proxy := range r.rawProxies(false) {
|
for _, proxy := range r.rawProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"type": r.Type().String(),
|
"type": r.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := r.single.Do(func() (interface{}, error) {
|
elm, _, _ := r.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(r.providers, touch), nil
|
return getProvidersProxies(r.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -54,7 +54,7 @@ func (s *Selector) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"type": s.Type().String(),
|
"type": s.Type().String(),
|
||||||
"now": s.Now(),
|
"now": s.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
@ -83,7 +83,7 @@ func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
elm, _, _ := s.single.Do(func() (interface{}, error) {
|
elm, _, _ := s.single.Do(func() (any, error) {
|
||||||
proxies := getProvidersProxies(s.providers, touch)
|
proxies := getProvidersProxies(s.providers, touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if proxy.Name() == s.selected {
|
if proxy.Name() == s.selected {
|
||||||
|
@ -58,7 +58,7 @@ func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := u.single.Do(func() (interface{}, error) {
|
elm, _, _ := u.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(u.providers, touch), nil
|
return getProvidersProxies(u.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -66,7 +66,7 @@ func (u *URLTest) proxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, _ := u.fastSingle.Do(func() (interface{}, error) {
|
elm, _, shared := u.fastSingle.Do(func() (any, error) {
|
||||||
proxies := u.proxies(touch)
|
proxies := u.proxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
@ -95,6 +95,9 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
|
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||||
|
touchProviders(u.providers)
|
||||||
|
}
|
||||||
|
|
||||||
return elm.(C.Proxy)
|
return elm.(C.Proxy)
|
||||||
}
|
}
|
||||||
@ -114,22 +117,20 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
for _, proxy := range u.proxies(false) {
|
for _, proxy := range u.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"type": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]interface{}) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
// tolerance
|
// tolerance
|
||||||
if elm, ok := config["tolerance"]; ok {
|
if tolerance, ok := config["tolerance"].(int); ok {
|
||||||
if tolerance, ok := elm.(int); ok {
|
|
||||||
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,6 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
if ip == nil {
|
if ip == nil {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: nil,
|
DstIP: nil,
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
@ -26,7 +25,6 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
return
|
return
|
||||||
} else if ip4 := ip.To4(); ip4 != nil {
|
} else if ip4 := ip.To4(); ip4 != nil {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
|
||||||
Host: "",
|
Host: "",
|
||||||
DstIP: ip4,
|
DstIP: ip4,
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
@ -35,7 +33,6 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv6,
|
|
||||||
Host: "",
|
Host: "",
|
||||||
DstIP: ip,
|
DstIP: ip,
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
|
@ -16,17 +16,18 @@ var (
|
|||||||
dirMode os.FileMode = 0o755
|
dirMode os.FileMode = 0o755
|
||||||
)
|
)
|
||||||
|
|
||||||
type parser = func([]byte) (interface{}, error)
|
type parser = func([]byte) (any, error)
|
||||||
|
|
||||||
type fetcher struct {
|
type fetcher struct {
|
||||||
name string
|
name string
|
||||||
vehicle types.Vehicle
|
vehicle types.Vehicle
|
||||||
|
interval time.Duration
|
||||||
updatedAt *time.Time
|
updatedAt *time.Time
|
||||||
ticker *time.Ticker
|
ticker *time.Ticker
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
hash [16]byte
|
hash [16]byte
|
||||||
parser parser
|
parser parser
|
||||||
onUpdate func(interface{})
|
onUpdate func(any)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) Name() string {
|
func (f *fetcher) Name() string {
|
||||||
@ -37,17 +38,19 @@ func (f *fetcher) VehicleType() types.VehicleType {
|
|||||||
return f.vehicle.Type()
|
return f.vehicle.Type()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) Initial() (interface{}, error) {
|
func (f *fetcher) Initial() (any, error) {
|
||||||
var (
|
var (
|
||||||
buf []byte
|
buf []byte
|
||||||
err error
|
err error
|
||||||
isLocal bool
|
isLocal bool
|
||||||
|
immediatelyUpdate bool
|
||||||
)
|
)
|
||||||
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
||||||
buf, err = os.ReadFile(f.vehicle.Path())
|
buf, err = os.ReadFile(f.vehicle.Path())
|
||||||
modTime := stat.ModTime()
|
modTime := stat.ModTime()
|
||||||
f.updatedAt = &modTime
|
f.updatedAt = &modTime
|
||||||
isLocal = true
|
isLocal = true
|
||||||
|
immediatelyUpdate = time.Since(modTime) > f.interval
|
||||||
} else {
|
} else {
|
||||||
buf, err = f.vehicle.Read()
|
buf, err = f.vehicle.Read()
|
||||||
}
|
}
|
||||||
@ -86,13 +89,13 @@ func (f *fetcher) Initial() (interface{}, error) {
|
|||||||
|
|
||||||
// pull proxies automatically
|
// pull proxies automatically
|
||||||
if f.ticker != nil {
|
if f.ticker != nil {
|
||||||
go f.pullLoop()
|
go f.pullLoop(immediatelyUpdate)
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) Update() (interface{}, bool, error) {
|
func (f *fetcher) Update() (any, bool, error) {
|
||||||
buf, err := f.vehicle.Read()
|
buf, err := f.vehicle.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
@ -102,6 +105,7 @@ func (f *fetcher) Update() (interface{}, bool, error) {
|
|||||||
hash := md5.Sum(buf)
|
hash := md5.Sum(buf)
|
||||||
if bytes.Equal(f.hash[:], hash[:]) {
|
if bytes.Equal(f.hash[:], hash[:]) {
|
||||||
f.updatedAt = &now
|
f.updatedAt = &now
|
||||||
|
os.Chtimes(f.vehicle.Path(), now, now)
|
||||||
return nil, true, nil
|
return nil, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,25 +133,33 @@ func (f *fetcher) Destroy() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher) pullLoop() {
|
func (f *fetcher) pullLoop(immediately bool) {
|
||||||
for {
|
update := func() {
|
||||||
select {
|
|
||||||
case <-f.ticker.C:
|
|
||||||
elm, same, err := f.Update()
|
elm, same, err := f.Update()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
||||||
continue
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if same {
|
if same {
|
||||||
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
||||||
continue
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Infoln("[Provider] %s's proxies update", f.Name())
|
log.Infoln("[Provider] %s's proxies update", f.Name())
|
||||||
if f.onUpdate != nil {
|
if f.onUpdate != nil {
|
||||||
f.onUpdate(elm)
|
f.onUpdate(elm)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if immediately {
|
||||||
|
update()
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-f.ticker.C:
|
||||||
|
update()
|
||||||
case <-f.done:
|
case <-f.done:
|
||||||
f.ticker.Stop()
|
f.ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -167,7 +179,7 @@ func safeWrite(path string, buf []byte) error {
|
|||||||
return os.WriteFile(path, buf, fileMode)
|
return os.WriteFile(path, buf, fileMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(interface{})) *fetcher {
|
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
|
||||||
var ticker *time.Ticker
|
var ticker *time.Ticker
|
||||||
if interval != 0 {
|
if interval != 0 {
|
||||||
ticker = time.NewTicker(interval)
|
ticker = time.NewTicker(interval)
|
||||||
@ -177,6 +189,7 @@ func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, pars
|
|||||||
name: name,
|
name: name,
|
||||||
ticker: ticker,
|
ticker: ticker,
|
||||||
vehicle: vehicle,
|
vehicle: vehicle,
|
||||||
|
interval: interval,
|
||||||
parser: parser,
|
parser: parser,
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
onUpdate: onUpdate,
|
onUpdate: onUpdate,
|
||||||
|
@ -7,6 +7,7 @@ import (
|
|||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"github.com/samber/lo"
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -31,13 +32,20 @@ type HealthCheck struct {
|
|||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
go hc.check()
|
go hc.checkAll()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
hc.check()
|
hc.checkAll()
|
||||||
|
} else { // lazy but still need to check not alive proxies
|
||||||
|
notAliveProxies := lo.Filter(hc.proxies, func(proxy C.Proxy, _ int) bool {
|
||||||
|
return !proxy.Alive()
|
||||||
|
})
|
||||||
|
if len(notAliveProxies) != 0 {
|
||||||
|
hc.check(notAliveProxies)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
@ -58,11 +66,15 @@ func (hc *HealthCheck) touch() {
|
|||||||
hc.lastTouch.Store(time.Now().Unix())
|
hc.lastTouch.Store(time.Now().Unix())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) checkAll() {
|
||||||
|
hc.check(hc.proxies)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) check(proxies []C.Proxy) {
|
||||||
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum(10))
|
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum(10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range proxies {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (interface{}, error) {
|
b.Go(p.Name(), func() (any, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
p.URLTest(ctx, hc.url)
|
p.URLTest(ctx, hc.url)
|
||||||
|
@ -10,7 +10,10 @@ import (
|
|||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errVehicleType = errors.New("unsupport vehicle type")
|
var (
|
||||||
|
errVehicleType = errors.New("unsupport vehicle type")
|
||||||
|
errSubPath = errors.New("path is not subpath of home directory")
|
||||||
|
)
|
||||||
|
|
||||||
type healthCheckSchema struct {
|
type healthCheckSchema struct {
|
||||||
Enable bool `provider:"enable"`
|
Enable bool `provider:"enable"`
|
||||||
@ -28,7 +31,7 @@ type proxyProviderSchema struct {
|
|||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]interface{}) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
@ -53,6 +56,9 @@ func ParseProxyProvider(name string, mapping map[string]interface{}) (types.Prox
|
|||||||
case "file":
|
case "file":
|
||||||
vehicle = NewFileVehicle(path)
|
vehicle = NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
|
if !C.Path.IsSubPath(path) {
|
||||||
|
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
||||||
|
}
|
||||||
vehicle = NewHTTPVehicle(schema.URL, path)
|
vehicle = NewHTTPVehicle(schema.URL, path)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
|
@ -4,23 +4,28 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
regexp "github.com/dlclark/regexp2"
|
||||||
|
"github.com/samber/lo"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var reject = adapter.NewProxy(outbound.NewReject())
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ReservedName = "default"
|
ReservedName = "default"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ProxySchema struct {
|
type ProxySchema struct {
|
||||||
Proxies []map[string]interface{} `yaml:"proxies"`
|
Proxies []map[string]any `yaml:"proxies"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// for auto gc
|
// for auto gc
|
||||||
@ -35,7 +40,7 @@ type proxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"name": pp.Name(),
|
"name": pp.Name(),
|
||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
@ -49,7 +54,7 @@ func (pp *proxySetProvider) Name() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) HealthCheck() {
|
func (pp *proxySetProvider) HealthCheck() {
|
||||||
pp.healthCheck.check()
|
pp.healthCheck.checkAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Update() error {
|
func (pp *proxySetProvider) Update() error {
|
||||||
@ -78,16 +83,15 @@ func (pp *proxySetProvider) Proxies() []C.Proxy {
|
|||||||
return pp.proxies
|
return pp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
func (pp *proxySetProvider) Touch() {
|
||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
return pp.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
go pp.healthCheck.check()
|
go pp.healthCheck.checkAll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,7 +101,7 @@ func stopProxyProvider(pd *ProxySetProvider) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
filterReg, err := regexp.Compile(filter)
|
filterReg, err := regexp.Compile(filter, regexp.None)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
@ -111,12 +115,12 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
onUpdate := func(elm interface{}) {
|
onUpdate := func(elm any) {
|
||||||
ret := elm.([]C.Proxy)
|
ret := elm.([]C.Proxy)
|
||||||
pd.setProxies(ret)
|
pd.setProxies(ret)
|
||||||
}
|
}
|
||||||
|
|
||||||
proxiesParseAndFilter := func(buf []byte) (interface{}, error) {
|
proxiesParseAndFilter := func(buf []byte) (any, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
@ -129,9 +133,15 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
if name, ok := mapping["name"]; ok && len(filter) > 0 && !filterReg.MatchString(name.(string)) {
|
if name, ok := mapping["name"].(string); ok && len(filter) > 0 {
|
||||||
|
matched, err := filterReg.MatchString(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("regex filter failed: %w", err)
|
||||||
|
}
|
||||||
|
if !matched {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
}
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
@ -169,7 +179,7 @@ type compatibleProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]any{
|
||||||
"name": cp.Name(),
|
"name": cp.Name(),
|
||||||
"type": cp.Type().String(),
|
"type": cp.Type().String(),
|
||||||
"vehicleType": cp.VehicleType().String(),
|
"vehicleType": cp.VehicleType().String(),
|
||||||
@ -182,7 +192,7 @@ func (cp *compatibleProvider) Name() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) HealthCheck() {
|
func (cp *compatibleProvider) HealthCheck() {
|
||||||
cp.healthCheck.check()
|
cp.healthCheck.checkAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Update() error {
|
func (cp *compatibleProvider) Update() error {
|
||||||
@ -205,9 +215,8 @@ func (cp *compatibleProvider) Proxies() []C.Proxy {
|
|||||||
return cp.proxies
|
return cp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
func (cp *compatibleProvider) Touch() {
|
||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
return cp.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
@ -233,3 +242,81 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ types.ProxyProvider = (*FilterableProvider)(nil)
|
||||||
|
|
||||||
|
type FilterableProvider struct {
|
||||||
|
name string
|
||||||
|
providers []types.ProxyProvider
|
||||||
|
filterReg *regexp.Regexp
|
||||||
|
single *singledo.Single
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"name": fp.Name(),
|
||||||
|
"type": fp.Type().String(),
|
||||||
|
"vehicleType": fp.VehicleType().String(),
|
||||||
|
"proxies": fp.Proxies(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) Name() string {
|
||||||
|
return fp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) HealthCheck() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) Update() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) Initial() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) VehicleType() types.VehicleType {
|
||||||
|
return types.Compatible
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) Type() types.ProviderType {
|
||||||
|
return types.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) Proxies() []C.Proxy {
|
||||||
|
elm, _, _ := fp.single.Do(func() (any, error) {
|
||||||
|
proxies := lo.FlatMap(
|
||||||
|
fp.providers,
|
||||||
|
func(item types.ProxyProvider, _ int) []C.Proxy {
|
||||||
|
return lo.Filter(
|
||||||
|
item.Proxies(),
|
||||||
|
func(item C.Proxy, _ int) bool {
|
||||||
|
matched, _ := fp.filterReg.MatchString(item.Name())
|
||||||
|
return matched
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
proxies = append(proxies, reject)
|
||||||
|
}
|
||||||
|
return proxies, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fp *FilterableProvider) Touch() {
|
||||||
|
for _, provider := range fp.providers {
|
||||||
|
provider.Touch()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFilterableProvider(name string, providers []types.ProxyProvider, filterReg *regexp.Regexp) *FilterableProvider {
|
||||||
|
return &FilterableProvider{
|
||||||
|
name: name,
|
||||||
|
providers: providers,
|
||||||
|
filterReg: filterReg,
|
||||||
|
single: singledo.NewSingle(time.Second * 10),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
type Option = func(b *Batch)
|
type Option = func(b *Batch)
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Value interface{}
|
Value any
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,7 +38,7 @@ type Batch struct {
|
|||||||
cancel func()
|
cancel func()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Batch) Go(key string, fn func() (interface{}, error)) {
|
func (b *Batch) Go(key string, fn func() (any, error)) {
|
||||||
b.wg.Add(1)
|
b.wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer b.wg.Done()
|
defer b.wg.Done()
|
||||||
|
@ -14,11 +14,11 @@ func TestBatch(t *testing.T) {
|
|||||||
b, _ := New(context.Background())
|
b, _ := New(context.Background())
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
b.Go("foo", func() (interface{}, error) {
|
b.Go("foo", func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 100)
|
time.Sleep(time.Millisecond * 100)
|
||||||
return "foo", nil
|
return "foo", nil
|
||||||
})
|
})
|
||||||
b.Go("bar", func() (interface{}, error) {
|
b.Go("bar", func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 150)
|
time.Sleep(time.Millisecond * 150)
|
||||||
return "bar", nil
|
return "bar", nil
|
||||||
})
|
})
|
||||||
@ -45,7 +45,7 @@ func TestBatchWithConcurrencyNum(t *testing.T) {
|
|||||||
now := time.Now()
|
now := time.Now()
|
||||||
for i := 0; i < 7; i++ {
|
for i := 0; i < 7; i++ {
|
||||||
idx := i
|
idx := i
|
||||||
b.Go(strconv.Itoa(idx), func() (interface{}, error) {
|
b.Go(strconv.Itoa(idx), func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 100)
|
time.Sleep(time.Millisecond * 100)
|
||||||
return strconv.Itoa(idx), nil
|
return strconv.Itoa(idx), nil
|
||||||
})
|
})
|
||||||
@ -64,12 +64,12 @@ func TestBatchWithConcurrencyNum(t *testing.T) {
|
|||||||
func TestBatchContext(t *testing.T) {
|
func TestBatchContext(t *testing.T) {
|
||||||
b, ctx := New(context.Background())
|
b, ctx := New(context.Background())
|
||||||
|
|
||||||
b.Go("error", func() (interface{}, error) {
|
b.Go("error", func() (any, error) {
|
||||||
time.Sleep(time.Millisecond * 100)
|
time.Sleep(time.Millisecond * 100)
|
||||||
return nil, errors.New("test error")
|
return nil, errors.New("test error")
|
||||||
})
|
})
|
||||||
|
|
||||||
b.Go("ctx", func() (interface{}, error) {
|
b.Go("ctx", func() (any, error) {
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
})
|
})
|
||||||
|
106
common/cache/cache.go
vendored
106
common/cache/cache.go
vendored
@ -1,106 +0,0 @@
|
|||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Cache store element with a expired time
|
|
||||||
type Cache struct {
|
|
||||||
*cache
|
|
||||||
}
|
|
||||||
|
|
||||||
type cache struct {
|
|
||||||
mapping sync.Map
|
|
||||||
janitor *janitor
|
|
||||||
}
|
|
||||||
|
|
||||||
type element struct {
|
|
||||||
Expired time.Time
|
|
||||||
Payload interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put element in Cache with its ttl
|
|
||||||
func (c *cache) Put(key interface{}, payload interface{}, ttl time.Duration) {
|
|
||||||
c.mapping.Store(key, &element{
|
|
||||||
Payload: payload,
|
|
||||||
Expired: time.Now().Add(ttl),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get element in Cache, and drop when it expired
|
|
||||||
func (c *cache) Get(key interface{}) interface{} {
|
|
||||||
item, exist := c.mapping.Load(key)
|
|
||||||
if !exist {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
elm := item.(*element)
|
|
||||||
// expired
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return elm.Payload
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetWithExpire element in Cache with Expire Time
|
|
||||||
func (c *cache) GetWithExpire(key interface{}) (payload interface{}, expired time.Time) {
|
|
||||||
item, exist := c.mapping.Load(key)
|
|
||||||
if !exist {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
elm := item.(*element)
|
|
||||||
// expired
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return elm.Payload, elm.Expired
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cache) cleanup() {
|
|
||||||
c.mapping.Range(func(k, v interface{}) bool {
|
|
||||||
key := k.(string)
|
|
||||||
elm := v.(*element)
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
type janitor struct {
|
|
||||||
interval time.Duration
|
|
||||||
stop chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *janitor) process(c *cache) {
|
|
||||||
ticker := time.NewTicker(j.interval)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ticker.C:
|
|
||||||
c.cleanup()
|
|
||||||
case <-j.stop:
|
|
||||||
ticker.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopJanitor(c *Cache) {
|
|
||||||
c.janitor.stop <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// New return *Cache
|
|
||||||
func New(interval time.Duration) *Cache {
|
|
||||||
j := &janitor{
|
|
||||||
interval: interval,
|
|
||||||
stop: make(chan struct{}),
|
|
||||||
}
|
|
||||||
c := &cache{janitor: j}
|
|
||||||
go j.process(c)
|
|
||||||
C := &Cache{c}
|
|
||||||
runtime.SetFinalizer(C, stopJanitor)
|
|
||||||
return C
|
|
||||||
}
|
|
70
common/cache/cache_test.go
vendored
70
common/cache/cache_test.go
vendored
@ -1,70 +0,0 @@
|
|||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCache_Basic(t *testing.T) {
|
|
||||||
interval := 200 * time.Millisecond
|
|
||||||
ttl := 20 * time.Millisecond
|
|
||||||
c := New(interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
c.Put("string", "a", ttl)
|
|
||||||
|
|
||||||
i := c.Get("int")
|
|
||||||
assert.Equal(t, i.(int), 1, "should recv 1")
|
|
||||||
|
|
||||||
s := c.Get("string")
|
|
||||||
assert.Equal(t, s.(string), "a", "should recv 'a'")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_TTL(t *testing.T) {
|
|
||||||
interval := 200 * time.Millisecond
|
|
||||||
ttl := 20 * time.Millisecond
|
|
||||||
now := time.Now()
|
|
||||||
c := New(interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
c.Put("int2", 2, ttl)
|
|
||||||
|
|
||||||
i := c.Get("int")
|
|
||||||
_, expired := c.GetWithExpire("int2")
|
|
||||||
assert.Equal(t, i.(int), 1, "should recv 1")
|
|
||||||
assert.True(t, now.Before(expired))
|
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
|
||||||
i = c.Get("int")
|
|
||||||
j, _ := c.GetWithExpire("int2")
|
|
||||||
assert.Nil(t, i, "should recv nil")
|
|
||||||
assert.Nil(t, j, "should recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_AutoCleanup(t *testing.T) {
|
|
||||||
interval := 10 * time.Millisecond
|
|
||||||
ttl := 15 * time.Millisecond
|
|
||||||
c := New(interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
|
||||||
i := c.Get("int")
|
|
||||||
j, _ := c.GetWithExpire("int")
|
|
||||||
assert.Nil(t, i, "should recv nil")
|
|
||||||
assert.Nil(t, j, "should recv nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_AutoGC(t *testing.T) {
|
|
||||||
sign := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
interval := 10 * time.Millisecond
|
|
||||||
ttl := 15 * time.Millisecond
|
|
||||||
c := New(interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
sign <- struct{}{}
|
|
||||||
}()
|
|
||||||
|
|
||||||
<-sign
|
|
||||||
runtime.GC()
|
|
||||||
}
|
|
38
common/cache/lrucache.go
vendored
38
common/cache/lrucache.go
vendored
@ -12,7 +12,7 @@ import (
|
|||||||
type Option func(*LruCache)
|
type Option func(*LruCache)
|
||||||
|
|
||||||
// EvictCallback is used to get a callback when a cache entry is evicted
|
// EvictCallback is used to get a callback when a cache entry is evicted
|
||||||
type EvictCallback = func(key interface{}, value interface{})
|
type EvictCallback = func(key any, value any)
|
||||||
|
|
||||||
// WithEvict set the evict callback
|
// WithEvict set the evict callback
|
||||||
func WithEvict(cb EvictCallback) Option {
|
func WithEvict(cb EvictCallback) Option {
|
||||||
@ -57,18 +57,18 @@ type LruCache struct {
|
|||||||
maxAge int64
|
maxAge int64
|
||||||
maxSize int
|
maxSize int
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
cache map[interface{}]*list.Element
|
cache map[any]*list.Element
|
||||||
lru *list.List // Front is least-recent
|
lru *list.List // Front is least-recent
|
||||||
updateAgeOnGet bool
|
updateAgeOnGet bool
|
||||||
staleReturn bool
|
staleReturn bool
|
||||||
onEvict EvictCallback
|
onEvict EvictCallback
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewLRUCache creates an LruCache
|
// New creates an LruCache
|
||||||
func NewLRUCache(options ...Option) *LruCache {
|
func New(options ...Option) *LruCache {
|
||||||
lc := &LruCache{
|
lc := &LruCache{
|
||||||
lru: list.New(),
|
lru: list.New(),
|
||||||
cache: make(map[interface{}]*list.Element),
|
cache: make(map[any]*list.Element),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
@ -78,9 +78,9 @@ func NewLRUCache(options ...Option) *LruCache {
|
|||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the interface{} representation of a cached response and a bool
|
// Get returns the any 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 any) (any, bool) {
|
||||||
entry := c.get(key)
|
entry := c.get(key)
|
||||||
if entry == nil {
|
if entry == nil {
|
||||||
return nil, false
|
return nil, false
|
||||||
@ -90,11 +90,11 @@ func (c *LruCache) Get(key interface{}) (interface{}, bool) {
|
|||||||
return value, true
|
return value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire returns the interface{} representation of a cached response,
|
// GetWithExpire returns the any representation of a cached response,
|
||||||
// a time.Time Give expected expires,
|
// a time.Time Give expected expires,
|
||||||
// and a bool set to true if the key was found.
|
// 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.
|
// 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) {
|
func (c *LruCache) GetWithExpire(key any) (any, time.Time, bool) {
|
||||||
entry := c.get(key)
|
entry := c.get(key)
|
||||||
if entry == nil {
|
if entry == nil {
|
||||||
return nil, time.Time{}, false
|
return nil, time.Time{}, false
|
||||||
@ -104,7 +104,7 @@ func (c *LruCache) GetWithExpire(key interface{}) (interface{}, time.Time, bool)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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 any) bool {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@ -112,8 +112,8 @@ func (c *LruCache) Exist(key interface{}) bool {
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set stores the interface{} representation of a response for a given key.
|
// Set stores the any representation of a response for a given key.
|
||||||
func (c *LruCache) Set(key interface{}, value interface{}) {
|
func (c *LruCache) Set(key any, value any) {
|
||||||
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
|
||||||
@ -121,9 +121,9 @@ func (c *LruCache) Set(key interface{}, value interface{}) {
|
|||||||
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetWithExpire stores the interface{} representation of a response for a given key and given expires.
|
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
||||||
// The expires time will round to second.
|
// The expires time will round to second.
|
||||||
func (c *LruCache) SetWithExpire(key interface{}, value interface{}, expires time.Time) {
|
func (c *LruCache) SetWithExpire(key any, value any, expires time.Time) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@ -155,7 +155,7 @@ func (c *LruCache) CloneTo(n *LruCache) {
|
|||||||
defer n.mu.Unlock()
|
defer n.mu.Unlock()
|
||||||
|
|
||||||
n.lru = list.New()
|
n.lru = list.New()
|
||||||
n.cache = make(map[interface{}]*list.Element)
|
n.cache = make(map[any]*list.Element)
|
||||||
|
|
||||||
for e := c.lru.Front(); e != nil; e = e.Next() {
|
for e := c.lru.Front(); e != nil; e = e.Next() {
|
||||||
elm := e.Value.(*entry)
|
elm := e.Value.(*entry)
|
||||||
@ -163,7 +163,7 @@ func (c *LruCache) CloneTo(n *LruCache) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache) get(key interface{}) *entry {
|
func (c *LruCache) get(key any) *entry {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@ -188,7 +188,7 @@ func (c *LruCache) get(key interface{}) *entry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete removes the value associated with a key.
|
// Delete removes the value associated with a key.
|
||||||
func (c *LruCache) Delete(key interface{}) {
|
func (c *LruCache) Delete(key any) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
@ -217,7 +217,7 @@ func (c *LruCache) deleteElement(le *list.Element) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type entry struct {
|
type entry struct {
|
||||||
key interface{}
|
key any
|
||||||
value interface{}
|
value any
|
||||||
expires int64
|
expires int64
|
||||||
}
|
}
|
||||||
|
22
common/cache/lrucache_test.go
vendored
22
common/cache/lrucache_test.go
vendored
@ -19,7 +19,7 @@ var entries = []struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUCache(t *testing.T) {
|
func TestLRUCache(t *testing.T) {
|
||||||
c := NewLRUCache()
|
c := New()
|
||||||
|
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
c.Set(e.key, e.value)
|
c.Set(e.key, e.value)
|
||||||
@ -45,7 +45,7 @@ func TestLRUCache(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUMaxAge(t *testing.T) {
|
func TestLRUMaxAge(t *testing.T) {
|
||||||
c := NewLRUCache(WithAge(86400))
|
c := New(WithAge(86400))
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expected := now + 86400
|
expected := now + 86400
|
||||||
@ -88,7 +88,7 @@ func TestLRUMaxAge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUpdateOnGet(t *testing.T) {
|
func TestLRUpdateOnGet(t *testing.T) {
|
||||||
c := NewLRUCache(WithAge(86400), WithUpdateAgeOnGet())
|
c := New(WithAge(86400), WithUpdateAgeOnGet())
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expires := now + 86400/2
|
expires := now + 86400/2
|
||||||
@ -103,7 +103,7 @@ func TestLRUpdateOnGet(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestMaxSize(t *testing.T) {
|
func TestMaxSize(t *testing.T) {
|
||||||
c := NewLRUCache(WithSize(2))
|
c := New(WithSize(2))
|
||||||
// Add one expired entry
|
// Add one expired entry
|
||||||
c.Set("foo", "bar")
|
c.Set("foo", "bar")
|
||||||
_, ok := c.Get("foo")
|
_, ok := c.Get("foo")
|
||||||
@ -117,7 +117,7 @@ func TestMaxSize(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExist(t *testing.T) {
|
func TestExist(t *testing.T) {
|
||||||
c := NewLRUCache(WithSize(1))
|
c := New(WithSize(1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
assert.True(t, c.Exist(1))
|
assert.True(t, c.Exist(1))
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
@ -126,11 +126,11 @@ func TestExist(t *testing.T) {
|
|||||||
|
|
||||||
func TestEvict(t *testing.T) {
|
func TestEvict(t *testing.T) {
|
||||||
temp := 0
|
temp := 0
|
||||||
evict := func(key interface{}, value interface{}) {
|
evict := func(key any, value any) {
|
||||||
temp = key.(int) + value.(int)
|
temp = key.(int) + value.(int)
|
||||||
}
|
}
|
||||||
|
|
||||||
c := NewLRUCache(WithEvict(evict), WithSize(1))
|
c := New(WithEvict(evict), WithSize(1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
|
|
||||||
@ -138,7 +138,7 @@ func TestEvict(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSetWithExpire(t *testing.T) {
|
func TestSetWithExpire(t *testing.T) {
|
||||||
c := NewLRUCache(WithAge(1))
|
c := New(WithAge(1))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -152,7 +152,7 @@ func TestSetWithExpire(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStale(t *testing.T) {
|
func TestStale(t *testing.T) {
|
||||||
c := NewLRUCache(WithAge(1), WithStale(true))
|
c := New(WithAge(1), WithStale(true))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -165,11 +165,11 @@ func TestStale(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCloneTo(t *testing.T) {
|
func TestCloneTo(t *testing.T) {
|
||||||
o := NewLRUCache(WithSize(10))
|
o := New(WithSize(10))
|
||||||
o.Set("1", 1)
|
o.Set("1", 1)
|
||||||
o.Set("2", 2)
|
o.Set("2", 2)
|
||||||
|
|
||||||
n := NewLRUCache(WithSize(2))
|
n := New(WithSize(2))
|
||||||
n.Set("3", 3)
|
n.Set("3", 3)
|
||||||
n.Set("4", 4)
|
n.Set("4", 4)
|
||||||
|
|
||||||
|
24
common/net/relay.go
Normal file
24
common/net/relay.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
ch := make(chan error)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
|
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
|
leftConn.SetReadDeadline(time.Now())
|
||||||
|
ch <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
|
rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
@ -1,3 +1,3 @@
|
|||||||
package observable
|
package observable
|
||||||
|
|
||||||
type Iterable <-chan interface{}
|
type Iterable <-chan any
|
||||||
|
@ -9,8 +9,8 @@ import (
|
|||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator(item []interface{}) chan interface{} {
|
func iterator(item []any) chan any {
|
||||||
ch := make(chan interface{})
|
ch := make(chan any)
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(100 * time.Millisecond)
|
time.Sleep(100 * time.Millisecond)
|
||||||
for _, elm := range item {
|
for _, elm := range item {
|
||||||
@ -22,7 +22,7 @@ func iterator(item []interface{}) chan interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable(t *testing.T) {
|
func TestObservable(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@ -34,7 +34,7 @@ func TestObservable(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_MultiSubscribe(t *testing.T) {
|
func TestObservable_MultiSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
ch1, _ := src.Subscribe()
|
ch1, _ := src.Subscribe()
|
||||||
ch2, _ := src.Subscribe()
|
ch2, _ := src.Subscribe()
|
||||||
@ -42,7 +42,7 @@ func TestObservable_MultiSubscribe(t *testing.T) {
|
|||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan any) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count.Inc()
|
count.Inc()
|
||||||
}
|
}
|
||||||
@ -55,7 +55,7 @@ func TestObservable_MultiSubscribe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribe(t *testing.T) {
|
func TestObservable_UnSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
@ -65,7 +65,7 @@ func TestObservable_UnSubscribe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1})
|
iter := iterator([]any{1})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, _ := src.Subscribe()
|
data, _ := src.Subscribe()
|
||||||
<-data
|
<-data
|
||||||
@ -75,14 +75,14 @@ func TestObservable_SubscribeClosedSource(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
||||||
sub := Subscription(make(chan interface{}))
|
sub := Subscription(make(chan any))
|
||||||
iter := iterator([]interface{}{1})
|
iter := iterator([]any{1})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
src.UnSubscribe(sub)
|
src.UnSubscribe(sub)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]any{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
max := 100
|
max := 100
|
||||||
|
|
||||||
@ -94,7 +94,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(max)
|
wg.Add(max)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan any) {
|
||||||
for range ch {
|
for range ch {
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
@ -115,7 +115,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_Observable_1000(b *testing.B) {
|
func Benchmark_Observable_1000(b *testing.B) {
|
||||||
ch := make(chan interface{})
|
ch := make(chan any)
|
||||||
o := NewObservable(ch)
|
o := NewObservable(ch)
|
||||||
num := 1000
|
num := 1000
|
||||||
|
|
||||||
|
@ -4,14 +4,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Subscription <-chan interface{}
|
type Subscription <-chan any
|
||||||
|
|
||||||
type Subscriber struct {
|
type Subscriber struct {
|
||||||
buffer chan interface{}
|
buffer chan any
|
||||||
once sync.Once
|
once sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscriber) Emit(item interface{}) {
|
func (s *Subscriber) Emit(item any) {
|
||||||
s.buffer <- item
|
s.buffer <- item
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,7 +27,7 @@ func (s *Subscriber) Close() {
|
|||||||
|
|
||||||
func newSubscriber() *Subscriber {
|
func newSubscriber() *Subscriber {
|
||||||
sub := &Subscriber{
|
sub := &Subscriber{
|
||||||
buffer: make(chan interface{}, 200),
|
buffer: make(chan any, 200),
|
||||||
}
|
}
|
||||||
return sub
|
return sub
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@ type Picker struct {
|
|||||||
|
|
||||||
once sync.Once
|
once sync.Once
|
||||||
errOnce sync.Once
|
errOnce sync.Once
|
||||||
result interface{}
|
result any
|
||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,7 +43,7 @@ func WithTimeout(ctx context.Context, timeout time.Duration) (*Picker, context.C
|
|||||||
|
|
||||||
// Wait blocks until all function calls from the Go method have returned,
|
// Wait blocks until all function calls from the Go method have returned,
|
||||||
// then returns the first nil error result (if any) from them.
|
// then returns the first nil error result (if any) from them.
|
||||||
func (p *Picker) Wait() interface{} {
|
func (p *Picker) Wait() any {
|
||||||
p.wg.Wait()
|
p.wg.Wait()
|
||||||
if p.cancel != nil {
|
if p.cancel != nil {
|
||||||
p.cancel()
|
p.cancel()
|
||||||
@ -58,7 +58,7 @@ func (p *Picker) Error() error {
|
|||||||
|
|
||||||
// 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() (any, error)) {
|
||||||
p.wg.Add(1)
|
p.wg.Add(1)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
|
@ -8,8 +8,8 @@ import (
|
|||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func sleepAndSend(ctx context.Context, delay int, input interface{}) func() (interface{}, error) {
|
func sleepAndSend(ctx context.Context, delay int, input any) func() (any, error) {
|
||||||
return func() (interface{}, error) {
|
return func() (any, error) {
|
||||||
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
||||||
select {
|
select {
|
||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
|
@ -23,7 +23,7 @@ func NewAllocator() *Allocator {
|
|||||||
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
||||||
for k := range alloc.buffers {
|
for k := range alloc.buffers {
|
||||||
i := k
|
i := k
|
||||||
alloc.buffers[k].New = func() interface{} {
|
alloc.buffers[k].New = func() any {
|
||||||
return make([]byte, 1<<uint32(i))
|
return make([]byte, 1<<uint32(i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -32,28 +32,37 @@ func NewAllocator() *Allocator {
|
|||||||
|
|
||||||
// Get a []byte from pool with most appropriate cap
|
// Get a []byte from pool with most appropriate cap
|
||||||
func (alloc *Allocator) Get(size int) []byte {
|
func (alloc *Allocator) Get(size int) []byte {
|
||||||
if size <= 0 || size > 65536 {
|
switch {
|
||||||
|
case size < 0:
|
||||||
|
panic("alloc.Get: len out of range")
|
||||||
|
case size == 0:
|
||||||
return nil
|
return nil
|
||||||
}
|
case size > 65536:
|
||||||
|
return make([]byte, size)
|
||||||
|
default:
|
||||||
bits := msb(size)
|
bits := msb(size)
|
||||||
if size == 1<<bits {
|
if size == 1<<bits {
|
||||||
return alloc.buffers[bits].Get().([]byte)[:size]
|
return alloc.buffers[bits].Get().([]byte)[:size]
|
||||||
}
|
}
|
||||||
|
|
||||||
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put returns a []byte to pool for future use,
|
// Put returns a []byte to pool for future use,
|
||||||
// which the cap must be exactly 2^n
|
// which the cap must be exactly 2^n
|
||||||
func (alloc *Allocator) Put(buf []byte) error {
|
func (alloc *Allocator) Put(buf []byte) error {
|
||||||
|
if cap(buf) == 0 || cap(buf) > 65536 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
bits := msb(cap(buf))
|
bits := msb(cap(buf))
|
||||||
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
|
if cap(buf) != 1<<bits {
|
||||||
return errors.New("allocator Put() incorrect buffer size")
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
}
|
}
|
||||||
|
|
||||||
//lint:ignore SA6002 ignore temporarily
|
|
||||||
//nolint
|
//nolint
|
||||||
|
//lint:ignore SA6002 ignore temporarily
|
||||||
alloc.buffers[bits].Put(buf)
|
alloc.buffers[bits].Put(buf)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -19,17 +19,17 @@ func TestAllocGet(t *testing.T) {
|
|||||||
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
||||||
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
||||||
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
||||||
assert.Nil(t, alloc.Get(65537))
|
assert.Equal(t, 65537, len(alloc.Get(65537)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAllocPut(t *testing.T) {
|
func TestAllocPut(t *testing.T) {
|
||||||
alloc := NewAllocator()
|
alloc := NewAllocator()
|
||||||
assert.NotNil(t, alloc.Put(nil), "put nil misbehavior")
|
assert.Nil(t, alloc.Put(nil), "put nil misbehavior")
|
||||||
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes 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, 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, 1023, 1024)), "put elem:1024 []bytes misbehavior")
|
||||||
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []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")
|
assert.Nil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAllocPutThenGet(t *testing.T) {
|
func TestAllocPutThenGet(t *testing.T) {
|
||||||
|
@ -3,9 +3,14 @@ package pool
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/protobytes"
|
||||||
)
|
)
|
||||||
|
|
||||||
var bufferPool = sync.Pool{New: func() interface{} { return &bytes.Buffer{} }}
|
var (
|
||||||
|
bufferPool = sync.Pool{New: func() any { return &bytes.Buffer{} }}
|
||||||
|
bytesBufferPool = sync.Pool{New: func() any { return &protobytes.BytesWriter{} }}
|
||||||
|
)
|
||||||
|
|
||||||
func GetBuffer() *bytes.Buffer {
|
func GetBuffer() *bytes.Buffer {
|
||||||
return bufferPool.Get().(*bytes.Buffer)
|
return bufferPool.Get().(*bytes.Buffer)
|
||||||
@ -15,3 +20,12 @@ func PutBuffer(buf *bytes.Buffer) {
|
|||||||
buf.Reset()
|
buf.Reset()
|
||||||
bufferPool.Put(buf)
|
bufferPool.Put(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetBytesBuffer() *protobytes.BytesWriter {
|
||||||
|
return bytesBufferPool.Get().(*protobytes.BytesWriter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PutBytesBuffer(buf *protobytes.BytesWriter) {
|
||||||
|
buf.Reset()
|
||||||
|
bytesBufferPool.Put(buf)
|
||||||
|
}
|
||||||
|
@ -6,12 +6,12 @@ import (
|
|||||||
|
|
||||||
// Queue is a simple concurrent safe queue
|
// Queue is a simple concurrent safe queue
|
||||||
type Queue struct {
|
type Queue struct {
|
||||||
items []interface{}
|
items []any
|
||||||
lock sync.RWMutex
|
lock sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put add the item to the queue.
|
// Put add the item to the queue.
|
||||||
func (q *Queue) Put(items ...interface{}) {
|
func (q *Queue) Put(items ...any) {
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -22,7 +22,7 @@ func (q *Queue) Put(items ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pop returns the head of items.
|
// Pop returns the head of items.
|
||||||
func (q *Queue) Pop() interface{} {
|
func (q *Queue) Pop() any {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -35,7 +35,7 @@ func (q *Queue) Pop() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Last returns the last of item.
|
// Last returns the last of item.
|
||||||
func (q *Queue) Last() interface{} {
|
func (q *Queue) Last() any {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -47,8 +47,8 @@ func (q *Queue) Last() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Copy get the copy of queue.
|
// Copy get the copy of queue.
|
||||||
func (q *Queue) Copy() []interface{} {
|
func (q *Queue) Copy() []any {
|
||||||
items := []interface{}{}
|
items := []any{}
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
items = append(items, q.items...)
|
items = append(items, q.items...)
|
||||||
q.lock.RUnlock()
|
q.lock.RUnlock()
|
||||||
@ -66,6 +66,6 @@ func (q *Queue) Len() int64 {
|
|||||||
// New is a constructor for a new concurrent safe queue.
|
// New is a constructor for a new concurrent safe queue.
|
||||||
func New(hint int64) *Queue {
|
func New(hint int64) *Queue {
|
||||||
return &Queue{
|
return &Queue{
|
||||||
items: make([]interface{}, 0, hint),
|
items: make([]any, 0, hint),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import (
|
|||||||
|
|
||||||
type call struct {
|
type call struct {
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
val interface{}
|
val any
|
||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -20,13 +20,12 @@ type Single struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
Val interface{}
|
Val any
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do single.Do likes sync.singleFlight
|
// Do single.Do likes sync.singleFlight
|
||||||
//lint:ignore ST1008 it likes sync.singleFlight
|
func (s *Single) Do(fn func() (any, error)) (v any, 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()
|
||||||
if now.Before(s.last.Add(s.wait)) {
|
if now.Before(s.last.Add(s.wait)) {
|
||||||
|
@ -13,7 +13,7 @@ func TestBasic(t *testing.T) {
|
|||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
shardCount := atomic.NewInt32(0)
|
shardCount := atomic.NewInt32(0)
|
||||||
call := func() (interface{}, error) {
|
call := func() (any, error) {
|
||||||
foo++
|
foo++
|
||||||
time.Sleep(time.Millisecond * 5)
|
time.Sleep(time.Millisecond * 5)
|
||||||
return nil, nil
|
return nil, nil
|
||||||
@ -40,7 +40,7 @@ func TestBasic(t *testing.T) {
|
|||||||
func TestTimer(t *testing.T) {
|
func TestTimer(t *testing.T) {
|
||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
call := func() (interface{}, error) {
|
call := func() (any, error) {
|
||||||
foo++
|
foo++
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@ -56,7 +56,7 @@ func TestTimer(t *testing.T) {
|
|||||||
func TestReset(t *testing.T) {
|
func TestReset(t *testing.T) {
|
||||||
single := NewSingle(time.Millisecond * 30)
|
single := NewSingle(time.Millisecond * 30)
|
||||||
foo := 0
|
foo := 0
|
||||||
call := func() (interface{}, error) {
|
call := func() (any, error) {
|
||||||
foo++
|
foo++
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !linux
|
//go:build !linux
|
||||||
// +build !linux
|
|
||||||
|
|
||||||
package sockopt
|
package sockopt
|
||||||
|
|
||||||
|
@ -28,8 +28,8 @@ func NewDecoder(option Option) *Decoder {
|
|||||||
return &Decoder{option: &option}
|
return &Decoder{option: &option}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode transform a map[string]interface{} to a struct
|
// Decode transform a map[string]any to a struct
|
||||||
func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||||
return fmt.Errorf("Decode must recive a ptr struct")
|
return fmt.Errorf("Decode must recive a ptr struct")
|
||||||
}
|
}
|
||||||
@ -45,12 +45,8 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tag := field.Tag.Get(d.option.TagName)
|
tag := field.Tag.Get(d.option.TagName)
|
||||||
str := strings.SplitN(tag, ",", 2)
|
key, omitKey, found := strings.Cut(tag, ",")
|
||||||
key := str[0]
|
omitempty := found && omitKey == "omitempty"
|
||||||
omitempty := false
|
|
||||||
if len(str) > 1 {
|
|
||||||
omitempty = str[1] == "omitempty"
|
|
||||||
}
|
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok || value == nil {
|
if !ok || value == nil {
|
||||||
@ -68,7 +64,7 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
switch val.Kind() {
|
switch val.Kind() {
|
||||||
case reflect.Int:
|
case reflect.Int:
|
||||||
return d.decodeInt(name, data, val)
|
return d.decodeInt(name, data, val)
|
||||||
@ -89,12 +85,14 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.Int:
|
case kind == reflect.Int:
|
||||||
val.SetInt(dataVal.Int())
|
val.SetInt(dataVal.Int())
|
||||||
|
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
|
||||||
|
val.SetInt(int64(dataVal.Float()))
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
var i int64
|
var i int64
|
||||||
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
||||||
@ -112,7 +110,7 @@ func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (e
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
@ -129,7 +127,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
@ -146,7 +144,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
||||||
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
@ -161,9 +159,19 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
for valSlice.Len() <= i {
|
for valSlice.Len() <= i {
|
||||||
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
||||||
}
|
}
|
||||||
currentField := valSlice.Index(i)
|
|
||||||
|
|
||||||
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
||||||
|
if currentData == nil {
|
||||||
|
// in weakly type mode, null will convert to zero value
|
||||||
|
if d.option.WeaklyTypedInput {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// in non-weakly type mode, null will convert to nil if element's zero value is nil, otherwise return an error
|
||||||
|
if elemKind := valElemType.Kind(); elemKind == reflect.Map || elemKind == reflect.Slice {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("'%s' can not be null", fieldName)
|
||||||
|
}
|
||||||
|
currentField := valSlice.Index(i)
|
||||||
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -173,7 +181,7 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeMap(name string, data any, val reflect.Value) error {
|
||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valKeyType := valType.Key()
|
valKeyType := valType.Key()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
@ -245,7 +253,7 @@ func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val refle
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
|
func (d *Decoder) decodeStruct(name string, data any, val reflect.Value) error {
|
||||||
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
|
||||||
// If the type of the value to write to and the data match directly,
|
// If the type of the value to write to and the data match directly,
|
||||||
@ -273,7 +281,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
}
|
}
|
||||||
|
|
||||||
dataValKeys := make(map[reflect.Value]struct{})
|
dataValKeys := make(map[reflect.Value]struct{})
|
||||||
dataValKeysUnused := make(map[interface{}]struct{})
|
dataValKeysUnused := make(map[any]struct{})
|
||||||
for _, dataValKey := range dataVal.MapKeys() {
|
for _, dataValKey := range dataVal.MapKeys() {
|
||||||
dataValKeys[dataValKey] = struct{}{}
|
dataValKeys[dataValKey] = struct{}{}
|
||||||
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
||||||
@ -398,7 +406,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) setInterface(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) setInterface(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
val.Set(dataVal)
|
val.Set(dataVal)
|
||||||
return nil
|
return nil
|
||||||
|
@ -27,7 +27,7 @@ type BazOptional struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Basic(t *testing.T) {
|
func TestStructure_Basic(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
"bar": "test",
|
"bar": "test",
|
||||||
"extra": false,
|
"extra": false,
|
||||||
@ -45,7 +45,7 @@ func TestStructure_Basic(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Slice(t *testing.T) {
|
func TestStructure_Slice(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
"bar": []string{"one", "two"},
|
"bar": []string{"one", "two"},
|
||||||
}
|
}
|
||||||
@ -62,7 +62,7 @@ func TestStructure_Slice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Optional(t *testing.T) {
|
func TestStructure_Optional(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,7 +77,7 @@ func TestStructure_Optional(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_MissingKey(t *testing.T) {
|
func TestStructure_MissingKey(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,14 +87,14 @@ func TestStructure_MissingKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_ParamError(t *testing.T) {
|
func TestStructure_ParamError(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{}
|
rawMap := map[string]any{}
|
||||||
s := Baz{}
|
s := Baz{}
|
||||||
err := decoder.Decode(rawMap, s)
|
err := decoder.Decode(rawMap, s)
|
||||||
assert.NotNilf(t, err, "should throw error: %#v", s)
|
assert.NotNilf(t, err, "should throw error: %#v", s)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_SliceTypeError(t *testing.T) {
|
func TestStructure_SliceTypeError(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
"bar": []int{1, 2},
|
"bar": []int{1, 2},
|
||||||
}
|
}
|
||||||
@ -105,7 +105,7 @@ func TestStructure_SliceTypeError(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_WeakType(t *testing.T) {
|
func TestStructure_WeakType(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": "1",
|
"foo": "1",
|
||||||
"bar": []int{1},
|
"bar": []int{1},
|
||||||
}
|
}
|
||||||
@ -122,7 +122,7 @@ func TestStructure_WeakType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_Nest(t *testing.T) {
|
func TestStructure_Nest(t *testing.T) {
|
||||||
rawMap := map[string]interface{}{
|
rawMap := map[string]any{
|
||||||
"foo": 1,
|
"foo": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -137,3 +137,45 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValue(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": []any{"bar", nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazSlice{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: []string{"bar", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := weakTypeDecoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, goal.Bar, s.Bar)
|
||||||
|
|
||||||
|
s = &BazSlice{}
|
||||||
|
err = decoder.Decode(rawMap, s)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &struct {
|
||||||
|
Bar []map[string]any `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Nil(t, s.Bar[1])
|
||||||
|
|
||||||
|
ss := &struct {
|
||||||
|
Bar []Baz `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = decoder.Decode(rawMap, ss)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
@ -36,7 +36,7 @@ func NewAuthenticator(users []AuthUser) Authenticator {
|
|||||||
au.storage.Store(user.User, user.Pass)
|
au.storage.Store(user.User, user.Pass)
|
||||||
}
|
}
|
||||||
usernames := make([]string, 0, len(users))
|
usernames := make([]string, 0, len(users))
|
||||||
au.storage.Range(func(key, value interface{}) bool {
|
au.storage.Range(func(key, value any) bool {
|
||||||
usernames = append(usernames, key.(string))
|
usernames = append(usernames, key.(string))
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
@ -14,5 +14,15 @@ func ListenDHCPClient(ctx context.Context, ifaceName string) (net.PacketConn, er
|
|||||||
listenAddr = "255.255.255.255:68"
|
listenAddr = "255.255.255.255:68"
|
||||||
}
|
}
|
||||||
|
|
||||||
return dialer.ListenPacket(ctx, "udp4", listenAddr, dialer.WithInterface(ifaceName), dialer.WithAddrReuse(true))
|
options := []dialer.Option{
|
||||||
|
dialer.WithInterface(ifaceName),
|
||||||
|
dialer.WithAddrReuse(true),
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallback bind on windows, because syscall bind can not receive broadcast
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
options = append(options, dialer.WithFallbackBind(true))
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialer.ListenPacket(ctx, "udp4", listenAddr, options...)
|
||||||
}
|
}
|
||||||
|
@ -4,9 +4,9 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/iface"
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type controlFn = func(network, address string, c syscall.RawConn) error
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
||||||
|
@ -1,58 +1,12 @@
|
|||||||
//go:build !linux && !darwin
|
//go:build !linux && !darwin && !windows
|
||||||
// +build !linux,!darwin
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"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 {
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination net.IP) error {
|
||||||
if !destination.IsGlobalUnicast() {
|
if !destination.IsGlobalUnicast() {
|
||||||
return nil
|
return nil
|
||||||
|
98
component/dialer/bind_windows.go
Normal file
98
component/dialer/bind_windows.go
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
IP_UNICAST_IF = 31
|
||||||
|
IPV6_UNICAST_IF = 31
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var innerErr error
|
||||||
|
err = c.Control(func(fd uintptr) {
|
||||||
|
if ipStr == "" && strings.HasPrefix(network, "udp") {
|
||||||
|
// When listening udp ":0", we should bind socket to interface4 and interface6 at the same time
|
||||||
|
// and ignore the error of bind6
|
||||||
|
_ = bindSocketToInterface6(windows.Handle(fd), ifaceIdx)
|
||||||
|
innerErr = bindSocketToInterface4(windows.Handle(fd), ifaceIdx)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
innerErr = bindSocketToInterface4(windows.Handle(fd), ifaceIdx)
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
innerErr = bindSocketToInterface6(windows.Handle(fd), ifaceIdx)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if innerErr != nil {
|
||||||
|
err = innerErr
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindSocketToInterface4(handle windows.Handle, ifaceIdx int) error {
|
||||||
|
// MSDN says for IPv4 this needs to be in net byte order, so that it's like an IP address with leading zeros.
|
||||||
|
// Ref: https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options
|
||||||
|
var bytes [4]byte
|
||||||
|
binary.BigEndian.PutUint32(bytes[:], uint32(ifaceIdx))
|
||||||
|
index := *(*uint32)(unsafe.Pointer(&bytes[0]))
|
||||||
|
err := windows.SetsockoptInt(handle, windows.IPPROTO_IP, IP_UNICAST_IF, int(index))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindSocketToInterface6(handle windows.Handle, ifaceIdx int) error {
|
||||||
|
return windows.SetsockoptInt(handle, windows.IPPROTO_IPV6, IPV6_UNICAST_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
|
||||||
|
}
|
@ -38,6 +38,7 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
||||||
cfg := &option{
|
cfg := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
|
routingMark: int(DefaultRoutingMark.Load()),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, o := range DefaultOptions {
|
for _, o := range DefaultOptions {
|
||||||
@ -50,7 +51,15 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
|
|
||||||
lc := &net.ListenConfig{}
|
lc := &net.ListenConfig{}
|
||||||
if cfg.interfaceName != "" {
|
if cfg.interfaceName != "" {
|
||||||
addr, err := bindIfaceToListenConfig(cfg.interfaceName, lc, network, address)
|
var (
|
||||||
|
addr string
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if cfg.fallbackBind {
|
||||||
|
addr, err = fallbackBindIfaceToListenConfig(cfg.interfaceName, lc, network, address)
|
||||||
|
} else {
|
||||||
|
addr, err = bindIfaceToListenConfig(cfg.interfaceName, lc, network, address)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -69,6 +78,7 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
func dialContext(ctx context.Context, network string, destination net.IP, port string, options []Option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination net.IP, port string, options []Option) (net.Conn, error) {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
|
routingMark: int(DefaultRoutingMark.Load()),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, o := range DefaultOptions {
|
for _, o := range DefaultOptions {
|
||||||
@ -81,10 +91,16 @@ func dialContext(ctx context.Context, network string, destination net.IP, port s
|
|||||||
|
|
||||||
dialer := &net.Dialer{}
|
dialer := &net.Dialer{}
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
|
if opt.fallbackBind {
|
||||||
|
if err := fallbackBindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if opt.routingMark != 0 {
|
if opt.routingMark != 0 {
|
||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
90
component/dialer/fallbackbind.go
Normal file
90
component/dialer/fallbackbind.go
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
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 fallbackBindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination net.IP) error {
|
||||||
|
if !destination.IsGlobalUnicast() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
local := uint64(0)
|
||||||
|
if dialer.LocalAddr != nil {
|
||||||
|
_, port, err := net.SplitHostPort(dialer.LocalAddr.String())
|
||||||
|
if err == nil {
|
||||||
|
local, _ = strconv.ParseUint(port, 10, 16)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := lookupLocalAddr(ifaceName, network, destination, int(local))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer.LocalAddr = addr
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fallbackBindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string) (string, error) {
|
||||||
|
_, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
port = "0"
|
||||||
|
}
|
||||||
|
|
||||||
|
local, _ := strconv.ParseUint(port, 10, 16)
|
||||||
|
|
||||||
|
addr, err := lookupLocalAddr(ifaceName, network, nil, int(local))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return addr.String(), nil
|
||||||
|
}
|
@ -1,5 +1,4 @@
|
|||||||
//go:build linux
|
//go:build linux
|
||||||
// +build linux
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
@ -32,13 +31,13 @@ func bindMarkToControl(mark int, chain controlFn) controlFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
var innerErr error
|
||||||
switch network {
|
err = c.Control(func(fd uintptr) {
|
||||||
case "tcp4", "udp4":
|
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||||
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
|
||||||
case "tcp6", "udp6":
|
|
||||||
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
if innerErr != nil {
|
||||||
|
err = innerErr
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !linux
|
//go:build !linux
|
||||||
// +build !linux
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -5,10 +5,12 @@ import "go.uber.org/atomic"
|
|||||||
var (
|
var (
|
||||||
DefaultOptions []Option
|
DefaultOptions []Option
|
||||||
DefaultInterface = atomic.NewString("")
|
DefaultInterface = atomic.NewString("")
|
||||||
|
DefaultRoutingMark = atomic.NewInt32(0)
|
||||||
)
|
)
|
||||||
|
|
||||||
type option struct {
|
type option struct {
|
||||||
interfaceName string
|
interfaceName string
|
||||||
|
fallbackBind bool
|
||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
}
|
}
|
||||||
@ -21,6 +23,12 @@ func WithInterface(name string) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithFallbackBind(fallback bool) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.fallbackBind = fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func WithAddrReuse(reuse bool) Option {
|
func WithAddrReuse(reuse bool) Option {
|
||||||
return func(opt *option) {
|
return func(opt *option) {
|
||||||
opt.addrReuse = reuse
|
opt.addrReuse = reuse
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows
|
//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows
|
||||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
|
@ -3,6 +3,7 @@ package fakeip
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
@ -20,7 +21,7 @@ type store interface {
|
|||||||
CloneTo(store)
|
CloneTo(store)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pool is a implementation about fake ip generator without storage
|
// Pool is an implementation about fake ip generator without storage
|
||||||
type Pool struct {
|
type Pool struct {
|
||||||
max uint32
|
max uint32
|
||||||
min uint32
|
min uint32
|
||||||
@ -36,6 +37,9 @@ type Pool struct {
|
|||||||
func (p *Pool) Lookup(host string) net.IP {
|
func (p *Pool) Lookup(host string) net.IP {
|
||||||
p.mux.Lock()
|
p.mux.Lock()
|
||||||
defer p.mux.Unlock()
|
defer p.mux.Unlock()
|
||||||
|
|
||||||
|
// RFC4343: DNS Case Insensitive, we SHOULD return result with all cases.
|
||||||
|
host = strings.ToLower(host)
|
||||||
if ip, exist := p.store.GetByHost(host); exist {
|
if ip, exist := p.store.GetByHost(host); exist {
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
@ -95,21 +99,21 @@ func (p *Pool) CloneFrom(o *Pool) {
|
|||||||
func (p *Pool) get(host string) net.IP {
|
func (p *Pool) get(host string) net.IP {
|
||||||
current := p.offset
|
current := p.offset
|
||||||
for {
|
for {
|
||||||
|
ip := uintToIP(p.min + p.offset)
|
||||||
|
if !p.store.Exist(ip) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
p.offset = (p.offset + 1) % (p.max - p.min)
|
p.offset = (p.offset + 1) % (p.max - p.min)
|
||||||
// Avoid infinite loops
|
// Avoid infinite loops
|
||||||
if p.offset == current {
|
if p.offset == current {
|
||||||
p.offset = (p.offset + 1) % (p.max - p.min)
|
p.offset = (p.offset + 1) % (p.max - p.min)
|
||||||
ip := uintToIP(p.min + p.offset - 1)
|
ip := uintToIP(p.min + p.offset)
|
||||||
p.store.DelByIP(ip)
|
p.store.DelByIP(ip)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := uintToIP(p.min + p.offset - 1)
|
|
||||||
if !p.store.Exist(ip) {
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
ip := uintToIP(p.min + p.offset)
|
||||||
ip := uintToIP(p.min + p.offset - 1)
|
|
||||||
p.store.PutByIP(ip, host)
|
p.store.PutByIP(ip, host)
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
@ -164,7 +168,7 @@ func New(options Options) (*Pool, error) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
pool.store = &memoryStore{
|
pool.store = &memoryStore{
|
||||||
cache: cache.NewLRUCache(cache.WithSize(options.Size * 2)),
|
cache: cache.New(cache.WithSize(options.Size * 2)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package fakeip
|
package fakeip
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
@ -75,6 +74,27 @@ func TestPool_Basic(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPool_Case_Insensitive(t *testing.T) {
|
||||||
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
||||||
|
pools, tempfile, err := createPools(Options{
|
||||||
|
IPNet: ipnet,
|
||||||
|
Size: 10,
|
||||||
|
})
|
||||||
|
assert.Nil(t, err)
|
||||||
|
defer os.Remove(tempfile)
|
||||||
|
|
||||||
|
for _, pool := range pools {
|
||||||
|
first := pool.Lookup("foo.com")
|
||||||
|
last := pool.Lookup("Foo.Com")
|
||||||
|
foo, exist := pool.LookBack(last)
|
||||||
|
|
||||||
|
assert.True(t, first.Equal(pool.Lookup("Foo.Com")))
|
||||||
|
assert.Equal(t, pool.Lookup("fOo.cOM"), first)
|
||||||
|
assert.True(t, exist)
|
||||||
|
assert.Equal(t, foo, "foo.com")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPool_CycleUsed(t *testing.T) {
|
func TestPool_CycleUsed(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
@ -85,15 +105,13 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
defer os.Remove(tempfile)
|
defer os.Remove(tempfile)
|
||||||
|
|
||||||
for _, pool := range pools {
|
for _, pool := range pools {
|
||||||
foo := pool.Lookup("foo.com")
|
assert.Equal(t, net.IP{192, 168, 0, 2}, pool.Lookup("2.com"))
|
||||||
bar := pool.Lookup("bar.com")
|
assert.Equal(t, net.IP{192, 168, 0, 3}, pool.Lookup("3.com"))
|
||||||
for i := 0; i < 3; i++ {
|
assert.Equal(t, net.IP{192, 168, 0, 4}, pool.Lookup("4.com"))
|
||||||
pool.Lookup(fmt.Sprintf("%d.com", i))
|
assert.Equal(t, net.IP{192, 168, 0, 5}, pool.Lookup("5.com"))
|
||||||
}
|
assert.Equal(t, net.IP{192, 168, 0, 6}, pool.Lookup("6.com"))
|
||||||
baz := pool.Lookup("baz.com")
|
assert.Equal(t, net.IP{192, 168, 0, 2}, pool.Lookup("12.com"))
|
||||||
next := pool.Lookup("foo.com")
|
assert.Equal(t, net.IP{192, 168, 0, 3}, pool.Lookup("3.com"))
|
||||||
assert.True(t, foo.Equal(baz))
|
|
||||||
assert.True(t, next.Equal(bar))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -23,7 +23,7 @@ var (
|
|||||||
var interfaces = singledo.NewSingle(time.Second * 20)
|
var interfaces = singledo.NewSingle(time.Second * 20)
|
||||||
|
|
||||||
func ResolveInterface(name string) (*Interface, error) {
|
func ResolveInterface(name string) (*Interface, error) {
|
||||||
value, err, _ := interfaces.Do(func() (interface{}, error) {
|
value, err, _ := interfaces.Do(func() (any, error) {
|
||||||
ifaces, err := net.Interfaces()
|
ifaces, err := net.Interfaces()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
22
component/ipset/ipset_linux.go
Normal file
22
component/ipset/ipset_linux.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package ipset
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Test whether the ip is in the set or not
|
||||||
|
func Test(setName string, ip net.IP) (bool, error) {
|
||||||
|
return netlink.IpsetTest(setName, &netlink.IPSetEntry{
|
||||||
|
IP: ip,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify dumps a specific ipset to check if we can use the set normally
|
||||||
|
func Verify(setName string) error {
|
||||||
|
_, err := netlink.IpsetList(setName)
|
||||||
|
return err
|
||||||
|
}
|
17
component/ipset/ipset_others.go
Normal file
17
component/ipset/ipset_others.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
//go:build !linux
|
||||||
|
|
||||||
|
package ipset
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Always return false in non-linux
|
||||||
|
func Test(setName string, ip net.IP) (bool, error) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Always pass in non-linux
|
||||||
|
func Verify(setName string) error {
|
||||||
|
return nil
|
||||||
|
}
|
@ -6,17 +6,17 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Factory = func(context.Context) (interface{}, error)
|
type Factory = func(context.Context) (any, error)
|
||||||
|
|
||||||
type entry struct {
|
type entry struct {
|
||||||
elm interface{}
|
elm any
|
||||||
time time.Time
|
time time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(*pool)
|
type Option func(*pool)
|
||||||
|
|
||||||
// WithEvict set the evict callback
|
// WithEvict set the evict callback
|
||||||
func WithEvict(cb func(interface{})) Option {
|
func WithEvict(cb func(any)) Option {
|
||||||
return func(p *pool) {
|
return func(p *pool) {
|
||||||
p.evict = cb
|
p.evict = cb
|
||||||
}
|
}
|
||||||
@ -32,7 +32,7 @@ func WithAge(maxAge int64) Option {
|
|||||||
// WithSize defined max size of Pool
|
// WithSize defined max size of Pool
|
||||||
func WithSize(maxSize int) Option {
|
func WithSize(maxSize int) Option {
|
||||||
return func(p *pool) {
|
return func(p *pool) {
|
||||||
p.ch = make(chan interface{}, maxSize)
|
p.ch = make(chan any, maxSize)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,13 +42,13 @@ type Pool struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type pool struct {
|
type pool struct {
|
||||||
ch chan interface{}
|
ch chan any
|
||||||
factory Factory
|
factory Factory
|
||||||
evict func(interface{})
|
evict func(any)
|
||||||
maxAge int64
|
maxAge int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *pool) GetContext(ctx context.Context) (interface{}, error) {
|
func (p *pool) GetContext(ctx context.Context) (any, error) {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@ -68,11 +68,11 @@ func (p *pool) GetContext(ctx context.Context) (interface{}, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *pool) Get() (interface{}, error) {
|
func (p *pool) Get() (any, error) {
|
||||||
return p.GetContext(context.Background())
|
return p.GetContext(context.Background())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *pool) Put(item interface{}) {
|
func (p *pool) Put(item any) {
|
||||||
e := &entry{
|
e := &entry{
|
||||||
elm: item,
|
elm: item,
|
||||||
time: time.Now(),
|
time: time.Now(),
|
||||||
@ -100,7 +100,7 @@ func recycle(p *Pool) {
|
|||||||
|
|
||||||
func New(factory Factory, options ...Option) *Pool {
|
func New(factory Factory, options ...Option) *Pool {
|
||||||
p := &pool{
|
p := &pool{
|
||||||
ch: make(chan interface{}, 10),
|
ch: make(chan any, 10),
|
||||||
factory: factory,
|
factory: factory,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,7 +10,7 @@ import (
|
|||||||
|
|
||||||
func lg() Factory {
|
func lg() Factory {
|
||||||
initial := -1
|
initial := -1
|
||||||
return func(context.Context) (interface{}, error) {
|
return func(context.Context) (any, error) {
|
||||||
initial++
|
initial++
|
||||||
return initial, nil
|
return initial, nil
|
||||||
}
|
}
|
||||||
@ -34,7 +34,7 @@ func TestPool_MaxSize(t *testing.T) {
|
|||||||
size := 5
|
size := 5
|
||||||
pool := New(g, WithSize(size))
|
pool := New(g, WithSize(size))
|
||||||
|
|
||||||
items := []interface{}{}
|
items := []any{}
|
||||||
|
|
||||||
for i := 0; i < size; i++ {
|
for i := 0; i < size; i++ {
|
||||||
item, _ := pool.Get()
|
item, _ := pool.Get()
|
||||||
|
@ -2,7 +2,7 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net"
|
"net/netip"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -16,6 +16,6 @@ const (
|
|||||||
UDP = "udp"
|
UDP = "udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func FindProcessName(network string, srcIP net.IP, srcPort int) (string, error) {
|
func FindProcessPath(network string, from netip.AddrPort, to netip.AddrPort) (string, error) {
|
||||||
return findProcessName(network, srcIP, srcPort)
|
return findProcessPath(network, from, to)
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,9 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"net"
|
"net/netip"
|
||||||
"path/filepath"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@ -16,7 +17,23 @@ const (
|
|||||||
proccallnumpidinfo = 0x2
|
proccallnumpidinfo = 0x2
|
||||||
)
|
)
|
||||||
|
|
||||||
func findProcessName(network string, ip net.IP, port int) (string, error) {
|
var structSize = func() int {
|
||||||
|
value, _ := syscall.Sysctl("kern.osrelease")
|
||||||
|
major, _, _ := strings.Cut(value, ".")
|
||||||
|
n, _ := strconv.ParseInt(major, 10, 64)
|
||||||
|
switch true {
|
||||||
|
case n >= 22:
|
||||||
|
return 408
|
||||||
|
default:
|
||||||
|
// 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))
|
||||||
|
return 384
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
func findProcessPath(network string, from netip.AddrPort, _ netip.AddrPort) (string, error) {
|
||||||
var spath string
|
var spath string
|
||||||
switch network {
|
switch network {
|
||||||
case TCP:
|
case TCP:
|
||||||
@ -27,7 +44,7 @@ func findProcessName(network string, ip net.IP, port int) (string, error) {
|
|||||||
return "", ErrInvalidNetwork
|
return "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
isIPv4 := ip.To4() != nil
|
isIPv4 := from.Addr().Is4()
|
||||||
|
|
||||||
value, err := syscall.Sysctl(spath)
|
value, err := syscall.Sysctl(spath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -35,50 +52,64 @@ func findProcessName(network string, ip net.IP, port int) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
buf := []byte(value)
|
buf := []byte(value)
|
||||||
|
itemSize := structSize
|
||||||
// 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 {
|
if network == TCP {
|
||||||
// rup8(sizeof(xtcpcb_n))
|
// rup8(sizeof(xtcpcb_n))
|
||||||
itemSize += 208
|
itemSize += 208
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var fallbackUDPProcess string
|
||||||
// skip the first xinpgen(24 bytes) block
|
// skip the first xinpgen(24 bytes) block
|
||||||
for i := 24; i+itemSize <= len(buf); i += itemSize {
|
for i := 24; i+itemSize <= len(buf); i += itemSize {
|
||||||
// offset of xinpcb_n and xsocket_n
|
// offset of xinpcb_n and xsocket_n
|
||||||
inp, so := i, i+104
|
inp, so := i, i+104
|
||||||
|
|
||||||
srcPort := binary.BigEndian.Uint16(buf[inp+18 : inp+20])
|
srcPort := binary.BigEndian.Uint16(buf[inp+18 : inp+20])
|
||||||
if uint16(port) != srcPort {
|
if from.Port() != srcPort {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FIXME: add dstPort check
|
||||||
|
|
||||||
// xinpcb_n.inp_vflag
|
// xinpcb_n.inp_vflag
|
||||||
flag := buf[inp+44]
|
flag := buf[inp+44]
|
||||||
|
|
||||||
var srcIP net.IP
|
var (
|
||||||
|
srcIP netip.Addr
|
||||||
|
srcIPOk bool
|
||||||
|
srcIsIPv4 bool
|
||||||
|
)
|
||||||
switch {
|
switch {
|
||||||
case flag&0x1 > 0 && isIPv4:
|
case flag&0x1 > 0 && isIPv4:
|
||||||
// ipv4
|
// ipv4
|
||||||
srcIP = net.IP(buf[inp+76 : inp+80])
|
srcIP, srcIPOk = netip.AddrFromSlice(buf[inp+76 : inp+80])
|
||||||
|
srcIsIPv4 = true
|
||||||
case flag&0x2 > 0 && !isIPv4:
|
case flag&0x2 > 0 && !isIPv4:
|
||||||
// ipv6
|
// ipv6
|
||||||
srcIP = net.IP(buf[inp+64 : inp+80])
|
srcIP, srcIPOk = netip.AddrFromSlice(buf[inp+64 : inp+80])
|
||||||
default:
|
default:
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if !srcIPOk {
|
||||||
if !ip.Equal(srcIP) {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if from.Addr() == srcIP { // FIXME: add dstIP check
|
||||||
// xsocket_n.so_last_pid
|
// xsocket_n.so_last_pid
|
||||||
pid := readNativeUint32(buf[so+68 : so+72])
|
pid := readNativeUint32(buf[so+68 : so+72])
|
||||||
return getExecPathFromPID(pid)
|
return getExecPathFromPID(pid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// udp packet connection may be not equal with srcIP
|
||||||
|
if network == UDP && srcIP.IsUnspecified() && isIPv4 == srcIsIPv4 {
|
||||||
|
fallbackUDPProcess, _ = getExecPathFromPID(readNativeUint32(buf[so+68 : so+72]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if network == UDP && fallbackUDPProcess != "" {
|
||||||
|
return fallbackUDPProcess, nil
|
||||||
|
}
|
||||||
|
|
||||||
return "", ErrNotFound
|
return "", ErrNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,7 +127,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
return "", errno
|
return "", errno
|
||||||
}
|
}
|
||||||
|
|
||||||
return filepath.Base(unix.ByteSliceToString(buf)), nil
|
return unix.ByteSliceToString(buf), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func readNativeUint32(b []byte) uint32 {
|
func readNativeUint32(b []byte) uint32 {
|
||||||
|
217
component/process/process_freebsd.go
Normal file
217
component/process/process_freebsd.go
Normal file
@ -0,0 +1,217 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Xinpgen12 [64]byte // size 64
|
||||||
|
|
||||||
|
type InEndpoints12 struct {
|
||||||
|
FPort [2]byte
|
||||||
|
LPort [2]byte
|
||||||
|
FAddr [16]byte
|
||||||
|
LAddr [16]byte
|
||||||
|
ZoneID uint32
|
||||||
|
} // size 40
|
||||||
|
|
||||||
|
type XTcpcb12 struct {
|
||||||
|
Len uint32 // offset 0
|
||||||
|
_ [20]byte // offset 4
|
||||||
|
SocketAddr uint64 // offset 24
|
||||||
|
_ [84]byte // offset 32
|
||||||
|
Family uint32 // offset 116
|
||||||
|
_ [140]byte // offset 120
|
||||||
|
InEndpoints InEndpoints12 // offset 260
|
||||||
|
_ [444]byte // offset 300
|
||||||
|
} // size 744
|
||||||
|
|
||||||
|
type XInpcb12 struct {
|
||||||
|
Len uint32 // offset 0
|
||||||
|
_ [12]byte // offset 4
|
||||||
|
SocketAddr uint64 // offset 16
|
||||||
|
_ [84]byte // offset 24
|
||||||
|
Family uint32 // offset 108
|
||||||
|
_ [140]byte // offset 112
|
||||||
|
InEndpoints InEndpoints12 // offset 252
|
||||||
|
_ [108]byte // offset 292
|
||||||
|
} // size 400
|
||||||
|
|
||||||
|
type XFile12 struct {
|
||||||
|
Size uint64 // offset 0
|
||||||
|
Pid uint32 // offset 8
|
||||||
|
_ [44]byte // offset 12
|
||||||
|
DataAddr uint64 // offset 56
|
||||||
|
_ [64]byte // offset 64
|
||||||
|
} // size 128
|
||||||
|
|
||||||
|
var majorVersion = func() int {
|
||||||
|
releaseVersion, err := unix.Sysctl("kern.osrelease")
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
majorVersionText, _, _ := strings.Cut(releaseVersion, ".")
|
||||||
|
|
||||||
|
majorVersion, err := strconv.Atoi(majorVersionText)
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
return majorVersion
|
||||||
|
}()
|
||||||
|
|
||||||
|
func findProcessPath(network string, from netip.AddrPort, to netip.AddrPort) (string, error) {
|
||||||
|
switch majorVersion {
|
||||||
|
case 12, 13:
|
||||||
|
return findProcessPath12(network, from, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", ErrPlatformNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func findProcessPath12(network string, from netip.AddrPort, to netip.AddrPort) (string, error) {
|
||||||
|
switch network {
|
||||||
|
case TCP:
|
||||||
|
data, err := unix.SysctlRaw("net.inet.tcp.pcblist")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(data) < int(unsafe.Sizeof(Xinpgen12{})) {
|
||||||
|
return "", fmt.Errorf("invalid sysctl data len: %d", len(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
data = data[unsafe.Sizeof(Xinpgen12{}):]
|
||||||
|
|
||||||
|
for len(data) > int(unsafe.Sizeof(XTcpcb12{}.Len)) {
|
||||||
|
tcb := (*XTcpcb12)(unsafe.Pointer(&data[0]))
|
||||||
|
if tcb.Len < uint32(unsafe.Sizeof(XTcpcb12{})) || uint32(len(data)) < tcb.Len {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
data = data[tcb.Len:]
|
||||||
|
|
||||||
|
var (
|
||||||
|
connFromAddr netip.Addr
|
||||||
|
connToAddr netip.Addr
|
||||||
|
)
|
||||||
|
if tcb.Family == unix.AF_INET {
|
||||||
|
connFromAddr = netip.AddrFrom4([4]byte(tcb.InEndpoints.LAddr[12:16]))
|
||||||
|
connToAddr = netip.AddrFrom4([4]byte(tcb.InEndpoints.FAddr[12:16]))
|
||||||
|
} else if tcb.Family == unix.AF_INET6 {
|
||||||
|
connFromAddr = netip.AddrFrom16(tcb.InEndpoints.LAddr)
|
||||||
|
connToAddr = netip.AddrFrom16(tcb.InEndpoints.FAddr)
|
||||||
|
} else {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
connFrom := netip.AddrPortFrom(connFromAddr, binary.BigEndian.Uint16(tcb.InEndpoints.LPort[:]))
|
||||||
|
connTo := netip.AddrPortFrom(connToAddr, binary.BigEndian.Uint16(tcb.InEndpoints.FPort[:]))
|
||||||
|
|
||||||
|
if connFrom == from && connTo == to {
|
||||||
|
pid, err := findPidBySocketAddr12(tcb.SocketAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return findExecutableByPid(pid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case UDP:
|
||||||
|
data, err := unix.SysctlRaw("net.inet.udp.pcblist")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(data) < int(unsafe.Sizeof(Xinpgen12{})) {
|
||||||
|
return "", fmt.Errorf("invalid sysctl data len: %d", len(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
data = data[unsafe.Sizeof(Xinpgen12{}):]
|
||||||
|
|
||||||
|
for len(data) > int(unsafe.Sizeof(XInpcb12{}.Len)) {
|
||||||
|
icb := (*XInpcb12)(unsafe.Pointer(&data[0]))
|
||||||
|
if icb.Len < uint32(unsafe.Sizeof(XInpcb12{})) || uint32(len(data)) < icb.Len {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
data = data[icb.Len:]
|
||||||
|
|
||||||
|
var connFromAddr netip.Addr
|
||||||
|
if icb.Family == unix.AF_INET {
|
||||||
|
connFromAddr = netip.AddrFrom4([4]byte(icb.InEndpoints.LAddr[12:16]))
|
||||||
|
} else if icb.Family == unix.AF_INET6 {
|
||||||
|
connFromAddr = netip.AddrFrom16(icb.InEndpoints.LAddr)
|
||||||
|
} else {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
connFromPort := binary.BigEndian.Uint16(icb.InEndpoints.LPort[:])
|
||||||
|
|
||||||
|
if (connFromAddr == from.Addr() || connFromAddr.IsUnspecified()) && connFromPort == from.Port() {
|
||||||
|
pid, err := findPidBySocketAddr12(icb.SocketAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return findExecutableByPid(pid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func findPidBySocketAddr12(socketAddr uint64) (uint32, error) {
|
||||||
|
buf, err := unix.SysctlRaw("kern.file")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
filesLen := len(buf) / int(unsafe.Sizeof(XFile12{}))
|
||||||
|
files := unsafe.Slice((*XFile12)(unsafe.Pointer(&buf[0])), filesLen)
|
||||||
|
|
||||||
|
for _, file := range files {
|
||||||
|
if file.Size != uint64(unsafe.Sizeof(XFile12{})) {
|
||||||
|
return 0, fmt.Errorf("invalid xfile size: %d", file.Size)
|
||||||
|
}
|
||||||
|
|
||||||
|
if file.DataAddr == socketAddr {
|
||||||
|
return file.Pid, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func findExecutableByPid(pid uint32) (string, error) {
|
||||||
|
buf := make([]byte, unix.PathMax)
|
||||||
|
size := uint64(len(buf))
|
||||||
|
mib := [4]uint32{
|
||||||
|
unix.CTL_KERN,
|
||||||
|
14, // KERN_PROC
|
||||||
|
12, // KERN_PROC_PATHNAME
|
||||||
|
pid,
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _, errno := unix.Syscall6(
|
||||||
|
unix.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 "", fmt.Errorf("sysctl: get proc name: %w", errno)
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(buf[:size-1]), nil
|
||||||
|
}
|
@ -1,234 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
35
component/process/process_freebsd_test.go
Normal file
35
component/process/process_freebsd_test.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
//go:build freebsd
|
||||||
|
|
||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEnforceStructValid12(t *testing.T) {
|
||||||
|
if majorVersion != 12 && majorVersion != 13 {
|
||||||
|
t.Skipf("Unsupported freebsd version: %d", majorVersion)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, 0, int(unsafe.Offsetof(XTcpcb12{}.Len)))
|
||||||
|
assert.Equal(t, 24, int(unsafe.Offsetof(XTcpcb12{}.SocketAddr)))
|
||||||
|
assert.Equal(t, 116, int(unsafe.Offsetof(XTcpcb12{}.Family)))
|
||||||
|
assert.Equal(t, 260, int(unsafe.Offsetof(XTcpcb12{}.InEndpoints)))
|
||||||
|
assert.Equal(t, 0, int(unsafe.Offsetof(XInpcb12{}.Len)))
|
||||||
|
assert.Equal(t, 16, int(unsafe.Offsetof(XInpcb12{}.SocketAddr)))
|
||||||
|
assert.Equal(t, 108, int(unsafe.Offsetof(XInpcb12{}.Family)))
|
||||||
|
assert.Equal(t, 252, int(unsafe.Offsetof(XInpcb12{}.InEndpoints)))
|
||||||
|
assert.Equal(t, 0, int(unsafe.Offsetof(XFile12{}.Size)))
|
||||||
|
assert.Equal(t, 8, int(unsafe.Offsetof(XFile12{}.Pid)))
|
||||||
|
assert.Equal(t, 56, int(unsafe.Offsetof(XFile12{}.DataAddr)))
|
||||||
|
assert.Equal(t, 64, int(unsafe.Sizeof(Xinpgen12{})))
|
||||||
|
assert.Equal(t, 744, int(unsafe.Sizeof(XTcpcb12{})))
|
||||||
|
assert.Equal(t, 400, int(unsafe.Sizeof(XInpcb12{})))
|
||||||
|
assert.Equal(t, 40, int(unsafe.Sizeof(InEndpoints12{})))
|
||||||
|
assert.Equal(t, 128, int(unsafe.Sizeof(XFile12{})))
|
||||||
|
}
|
@ -4,236 +4,226 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
|
||||||
"path/filepath"
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
|
||||||
|
"github.com/mdlayher/netlink"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
// from https://github.com/vishvananda/netlink/blob/bca67dfc8220b44ef582c9da4e9172bf1c9ec973/nl/nl_linux.go#L52-L62
|
type inetDiagRequest struct {
|
||||||
var nativeEndian = func() binary.ByteOrder {
|
Family byte
|
||||||
var x uint32 = 0x01020304
|
Protocol byte
|
||||||
if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
|
Ext byte
|
||||||
return binary.BigEndian
|
Pad byte
|
||||||
}
|
States uint32
|
||||||
|
|
||||||
return binary.LittleEndian
|
SrcPort [2]byte
|
||||||
}()
|
DstPort [2]byte
|
||||||
|
Src [16]byte
|
||||||
|
Dst [16]byte
|
||||||
|
If uint32
|
||||||
|
Cookie [2]uint32
|
||||||
|
}
|
||||||
|
|
||||||
type (
|
type inetDiagResponse struct {
|
||||||
SocketResolver func(network string, ip net.IP, srcPort int) (inode, uid int, err error)
|
Family byte
|
||||||
ProcessNameResolver func(inode, uid int) (name string, err error)
|
State byte
|
||||||
)
|
Timer byte
|
||||||
|
ReTrans byte
|
||||||
|
|
||||||
// export for android
|
SrcPort [2]byte
|
||||||
var (
|
DstPort [2]byte
|
||||||
DefaultSocketResolver SocketResolver = resolveSocketByNetlink
|
Src [16]byte
|
||||||
DefaultProcessNameResolver ProcessNameResolver = resolveProcessNameByProcSearch
|
Dst [16]byte
|
||||||
)
|
If uint32
|
||||||
|
Cookie [2]uint32
|
||||||
|
|
||||||
const (
|
Expires uint32
|
||||||
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48
|
RQueue uint32
|
||||||
socketDiagByFamily = 20
|
WQueue uint32
|
||||||
pathProc = "/proc"
|
UID uint32
|
||||||
)
|
INode uint32
|
||||||
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
func findProcessPath(network string, from netip.AddrPort, to netip.AddrPort) (string, error) {
|
||||||
inode, uid, err := DefaultSocketResolver(network, ip, srcPort)
|
inode, uid, err := resolveSocketByNetlink(network, from, to)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return DefaultProcessNameResolver(inode, uid)
|
return resolveProcessPathByProcSearch(inode, uid)
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, error) {
|
func resolveSocketByNetlink(network string, from netip.AddrPort, to netip.AddrPort) (inode uint32, uid uint32, err error) {
|
||||||
var family byte
|
var families []byte
|
||||||
var protocol byte
|
if from.Addr().Unmap().Is4() {
|
||||||
|
families = []byte{unix.AF_INET, unix.AF_INET6}
|
||||||
|
} else {
|
||||||
|
families = []byte{unix.AF_INET6, unix.AF_INET}
|
||||||
|
}
|
||||||
|
|
||||||
|
var protocol byte
|
||||||
switch network {
|
switch network {
|
||||||
case TCP:
|
case TCP:
|
||||||
protocol = syscall.IPPROTO_TCP
|
protocol = unix.IPPROTO_TCP
|
||||||
case UDP:
|
case UDP:
|
||||||
protocol = syscall.IPPROTO_UDP
|
protocol = unix.IPPROTO_UDP
|
||||||
default:
|
default:
|
||||||
return 0, 0, ErrInvalidNetwork
|
return 0, 0, ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip.To4() != nil {
|
if protocol == unix.IPPROTO_UDP {
|
||||||
family = syscall.AF_INET
|
// Swap from & to for udp
|
||||||
|
// See also https://www.mail-archive.com/netdev@vger.kernel.org/msg248638.html
|
||||||
|
from, to = to, from
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, family := range families {
|
||||||
|
inode, uid, err = resolveSocketByNetlinkExact(family, protocol, from, to, netlink.Request)
|
||||||
|
if err == nil {
|
||||||
|
return inode, uid, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, 0, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveSocketByNetlinkExact(family byte, protocol byte, from netip.AddrPort, to netip.AddrPort, flags netlink.HeaderFlags) (inode uint32, uid uint32, err error) {
|
||||||
|
request := &inetDiagRequest{
|
||||||
|
Family: family,
|
||||||
|
Protocol: protocol,
|
||||||
|
States: 0xffffffff,
|
||||||
|
Cookie: [2]uint32{0xffffffff, 0xffffffff},
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
fromAddr []byte
|
||||||
|
toAddr []byte
|
||||||
|
)
|
||||||
|
if family == unix.AF_INET {
|
||||||
|
fromAddr = net.IP(from.Addr().AsSlice()).To4()
|
||||||
|
toAddr = net.IP(to.Addr().AsSlice()).To4()
|
||||||
} else {
|
} else {
|
||||||
family = syscall.AF_INET6
|
fromAddr = net.IP(from.Addr().AsSlice()).To16()
|
||||||
|
toAddr = net.IP(to.Addr().AsSlice()).To16()
|
||||||
}
|
}
|
||||||
|
|
||||||
req := packSocketDiagRequest(family, protocol, ip, uint16(srcPort))
|
copy(request.Src[:], fromAddr)
|
||||||
|
copy(request.Dst[:], toAddr)
|
||||||
|
|
||||||
socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG)
|
binary.BigEndian.PutUint16(request.SrcPort[:], from.Port())
|
||||||
|
binary.BigEndian.PutUint16(request.DstPort[:], to.Port())
|
||||||
|
|
||||||
|
conn, err := netlink.Dial(unix.NETLINK_INET_DIAG, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
}
|
}
|
||||||
defer syscall.Close(socket)
|
defer conn.Close()
|
||||||
|
|
||||||
syscall.SetNonblock(socket, true)
|
message := netlink.Message{
|
||||||
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 50})
|
Header: netlink.Header{
|
||||||
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 50})
|
Type: 20, // SOCK_DIAG_BY_FAMILY
|
||||||
|
Flags: flags,
|
||||||
if err := syscall.Connect(socket, &syscall.SockaddrNetlink{
|
},
|
||||||
Family: syscall.AF_NETLINK,
|
Data: (*(*[unsafe.Sizeof(*request)]byte)(unsafe.Pointer(request)))[:],
|
||||||
Pad: 0,
|
|
||||||
Pid: 0,
|
|
||||||
Groups: 0,
|
|
||||||
}); err != nil {
|
|
||||||
return 0, 0, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := syscall.Write(socket, req); err != nil {
|
messages, err := conn.Execute(message)
|
||||||
return 0, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
rb := pool.Get(pool.RelayBufferSize)
|
|
||||||
defer pool.Put(rb)
|
|
||||||
|
|
||||||
n, err := syscall.Read(socket, rb)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
messages, err := syscall.ParseNetlinkMessage(rb[:n])
|
for _, msg := range messages {
|
||||||
|
if len(msg.Data) < int(unsafe.Sizeof(inetDiagResponse{})) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
response := (*inetDiagResponse)(unsafe.Pointer(&msg.Data[0]))
|
||||||
|
|
||||||
|
return response.INode, response.UID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, 0, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveProcessPathByProcSearch(inode, uid uint32) (string, error) {
|
||||||
|
procDir, err := os.Open("/proc")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return "", err
|
||||||
} else if len(messages) == 0 {
|
|
||||||
return 0, 0, io.ErrUnexpectedEOF
|
|
||||||
}
|
}
|
||||||
|
defer procDir.Close()
|
||||||
|
|
||||||
message := messages[0]
|
pids, err := procDir.Readdirnames(-1)
|
||||||
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 := os.ReadDir(pathProc)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer := make([]byte, syscall.PathMax)
|
expectedSocketName := fmt.Appendf(nil, "socket:[%d]", inode)
|
||||||
socket := []byte(fmt.Sprintf("socket:[%d]", inode))
|
|
||||||
|
|
||||||
for _, f := range files {
|
pathBuffer := pool.Get(64)
|
||||||
if !f.IsDir() || !isPid(f.Name()) {
|
defer pool.Put(pathBuffer)
|
||||||
|
|
||||||
|
readlinkBuffer := pool.Get(32)
|
||||||
|
defer pool.Put(readlinkBuffer)
|
||||||
|
|
||||||
|
copy(pathBuffer, "/proc/")
|
||||||
|
|
||||||
|
for _, pid := range pids {
|
||||||
|
if !isPid(pid) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
info, err := f.Info()
|
pathBuffer = append(pathBuffer[:len("/proc/")], pid...)
|
||||||
|
|
||||||
|
stat := &unix.Stat_t{}
|
||||||
|
err = unix.Stat(string(pathBuffer), stat)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
continue
|
||||||
}
|
} else if stat.Uid != uid {
|
||||||
if info.Sys().(*syscall.Stat_t).Uid != uint32(uid) {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
processPath := path.Join(pathProc, f.Name())
|
pathBuffer = append(pathBuffer, "/fd/"...)
|
||||||
fdPath := path.Join(processPath, "fd")
|
fdsPrefixLength := len(pathBuffer)
|
||||||
|
|
||||||
fds, err := os.ReadDir(fdPath)
|
fdDir, err := os.Open(string(pathBuffer))
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
fds, err := fdDir.Readdirnames(-1)
|
||||||
|
fdDir.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, fd := range fds {
|
for _, fd := range fds {
|
||||||
n, err := syscall.Readlink(path.Join(fdPath, fd.Name()), buffer)
|
pathBuffer = pathBuffer[:fdsPrefixLength]
|
||||||
|
|
||||||
|
pathBuffer = append(pathBuffer, fd...)
|
||||||
|
|
||||||
|
n, err := unix.Readlink(string(pathBuffer), readlinkBuffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
if bytes.Equal(readlinkBuffer[:n], expectedSocketName) {
|
||||||
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
return os.Readlink("/proc/" + pid + "/exe")
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return splitCmdline(cmdline), nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", syscall.ESRCH
|
return "", fmt.Errorf("inode %d of uid %d not found", inode, uid)
|
||||||
}
|
}
|
||||||
|
|
||||||
func splitCmdline(cmdline []byte) string {
|
func isPid(name string) bool {
|
||||||
indexOfEndOfString := len(cmdline)
|
for _, c := range name {
|
||||||
|
if c < '0' || c > '9' {
|
||||||
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 false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,11 @@
|
|||||||
//go:build !darwin && !linux && !windows && (!freebsd || !amd64)
|
//go:build !darwin && !linux && !windows && !freebsd
|
||||||
// +build !darwin
|
|
||||||
// +build !linux
|
|
||||||
// +build !windows
|
|
||||||
// +build !freebsd !amd64
|
|
||||||
|
|
||||||
package process
|
package process
|
||||||
|
|
||||||
import "net"
|
import (
|
||||||
|
"net/netip"
|
||||||
|
)
|
||||||
|
|
||||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
func findProcessPath(_ string, _, _ netip.AddrPort) (string, error) {
|
||||||
return "", ErrPlatformNotSupport
|
return "", ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
112
component/process/process_test.go
Normal file
112
component/process/process_test.go
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testConn(t *testing.T, network, address string) {
|
||||||
|
l, err := net.Listen(network, address)
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Listen failed", err)
|
||||||
|
}
|
||||||
|
defer l.Close()
|
||||||
|
|
||||||
|
conn, err := net.Dial("tcp", l.Addr().String())
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Dial failed", err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
rConn, err := l.Accept()
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Accept conn failed", err)
|
||||||
|
}
|
||||||
|
defer rConn.Close()
|
||||||
|
|
||||||
|
path, err := FindProcessPath(TCP, conn.LocalAddr().(*net.TCPAddr).AddrPort(), conn.RemoteAddr().(*net.TCPAddr).AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Find process path failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
exePath, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Get executable failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, exePath, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindProcessPathTCP(t *testing.T) {
|
||||||
|
t.Run("v4", func(t *testing.T) {
|
||||||
|
testConn(t, "tcp4", "127.0.0.1:0")
|
||||||
|
})
|
||||||
|
t.Run("v6", func(t *testing.T) {
|
||||||
|
testConn(t, "tcp6", "[::1]:0")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPacketConn(t *testing.T, network, lAddress, rAddress string) {
|
||||||
|
lConn, err := net.ListenPacket(network, lAddress)
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "ListenPacket failed", err)
|
||||||
|
}
|
||||||
|
defer lConn.Close()
|
||||||
|
|
||||||
|
rConn, err := net.ListenPacket(network, rAddress)
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "ListenPacket failed", err)
|
||||||
|
}
|
||||||
|
defer rConn.Close()
|
||||||
|
|
||||||
|
_, err = lConn.WriteTo([]byte{0}, rConn.LocalAddr())
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Send message failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, lAddr, err := rConn.ReadFrom([]byte{0})
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Receive message failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
path, err := FindProcessPath(UDP, lAddr.(*net.UDPAddr).AddrPort(), rConn.LocalAddr().(*net.UDPAddr).AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Find process path", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
exePath, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
assert.FailNow(t, "Find executable", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, exePath, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindProcessPathUDP(t *testing.T) {
|
||||||
|
t.Run("v4", func(t *testing.T) {
|
||||||
|
testPacketConn(t, "udp4", "127.0.0.1:0", "127.0.0.1:0")
|
||||||
|
})
|
||||||
|
t.Run("v6", func(t *testing.T) {
|
||||||
|
testPacketConn(t, "udp6", "[::1]:0", "[::1]:0")
|
||||||
|
})
|
||||||
|
t.Run("v4AnyLocal", func(t *testing.T) {
|
||||||
|
testPacketConn(t, "udp4", "0.0.0.0:0", "127.0.0.1:0")
|
||||||
|
})
|
||||||
|
t.Run("v6AnyLocal", func(t *testing.T) {
|
||||||
|
testPacketConn(t, "udp6", "[::]:0", "[::1]:0")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkFindProcessName(b *testing.B) {
|
||||||
|
from := netip.MustParseAddrPort("127.0.0.1:11447")
|
||||||
|
to := netip.MustParseAddrPort("127.0.0.1:33669")
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
FindProcessPath(TCP, from, to)
|
||||||
|
}
|
||||||
|
}
|
@ -1,195 +1,204 @@
|
|||||||
package process
|
package process
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net/netip"
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
tcpTableFunc = "GetExtendedTcpTable"
|
|
||||||
tcpTablePidConn = 4
|
|
||||||
udpTableFunc = "GetExtendedUdpTable"
|
|
||||||
udpTablePid = 1
|
|
||||||
queryProcNameFunc = "QueryFullProcessImageNameW"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
getExTCPTable uintptr
|
modIphlpapi = windows.NewLazySystemDLL("iphlpapi.dll")
|
||||||
getExUDPTable uintptr
|
|
||||||
queryProcName uintptr
|
|
||||||
|
|
||||||
once sync.Once
|
procGetExtendedTcpTable = modIphlpapi.NewProc("GetExtendedTcpTable")
|
||||||
|
procGetExtendedUdpTable = modIphlpapi.NewProc("GetExtendedUdpTable")
|
||||||
)
|
)
|
||||||
|
|
||||||
func initWin32API() error {
|
func findProcessPath(network string, from netip.AddrPort, to netip.AddrPort) (string, error) {
|
||||||
h, err := windows.LoadLibrary("iphlpapi.dll")
|
family := uint32(windows.AF_INET)
|
||||||
if err != nil {
|
if from.Addr().Is6() {
|
||||||
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
|
family = windows.AF_INET6
|
||||||
}
|
}
|
||||||
|
|
||||||
var class int
|
var protocol uint32
|
||||||
var fn uintptr
|
|
||||||
switch network {
|
switch network {
|
||||||
case TCP:
|
case TCP:
|
||||||
fn = getExTCPTable
|
protocol = windows.IPPROTO_TCP
|
||||||
class = tcpTablePidConn
|
|
||||||
case UDP:
|
case UDP:
|
||||||
fn = getExUDPTable
|
protocol = windows.IPPROTO_UDP
|
||||||
class = udpTablePid
|
|
||||||
default:
|
default:
|
||||||
return "", ErrInvalidNetwork
|
return "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
buf, err := getTransportTable(fn, family, class)
|
pid, err := findPidByConnectionEndpoint(family, protocol, from, to)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
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)
|
return getExecPathFromPID(pid)
|
||||||
}
|
}
|
||||||
|
|
||||||
type searcher struct {
|
func findPidByConnectionEndpoint(family uint32, protocol uint32, from netip.AddrPort, to netip.AddrPort) (uint32, error) {
|
||||||
itemSize int
|
buf := pool.Get(0)
|
||||||
port int
|
defer pool.Put(buf)
|
||||||
ip int
|
|
||||||
ipSize int
|
|
||||||
pid int
|
|
||||||
tcpState int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *searcher) Search(b []byte, ip net.IP, port uint16) (uint32, error) {
|
bufSize := uint32(len(buf))
|
||||||
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 {
|
loop:
|
||||||
tcpState := readNativeUint32(row[s.tcpState : s.tcpState+4])
|
for {
|
||||||
// MIB_TCP_STATE_ESTAB, only check established connections for TCP
|
var ret uintptr
|
||||||
if tcpState != 5 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// according to MSDN, only the lower 16 bits of dwLocalPort are used and the port number is in network endian.
|
switch protocol {
|
||||||
// this field can be illustrated as follows depends on different machine endianess:
|
case windows.IPPROTO_TCP:
|
||||||
// little endian: [ MSB LSB 0 0 ] interpret as native uint32 is ((LSB<<8)|MSB)
|
ret, _, _ = procGetExtendedTcpTable.Call(
|
||||||
// big endian: [ 0 0 MSB LSB ] interpret as native uint32 is ((MSB<<8)|LSB)
|
uintptr(unsafe.Pointer(unsafe.SliceData(buf))),
|
||||||
// so we need an syscall.Ntohs on the lower 16 bits after read the port as native uint32
|
uintptr(unsafe.Pointer(&bufSize)),
|
||||||
srcPort := syscall.Ntohs(uint16(readNativeUint32(row[s.port : s.port+4])))
|
0,
|
||||||
if srcPort != port {
|
uintptr(family),
|
||||||
continue
|
4, // TCP_TABLE_OWNER_PID_CONNECTIONS
|
||||||
}
|
0,
|
||||||
|
)
|
||||||
srcIP := net.IP(row[s.ip : s.ip+s.ipSize])
|
case windows.IPPROTO_UDP:
|
||||||
// windows binds an unbound udp socket to 0.0.0.0/[::] while first sendto
|
ret, _, _ = procGetExtendedUdpTable.Call(
|
||||||
if !ip.Equal(srcIP) && (!srcIP.IsUnspecified() || s.tcpState != -1) {
|
uintptr(unsafe.Pointer(unsafe.SliceData(buf))),
|
||||||
continue
|
uintptr(unsafe.Pointer(&bufSize)),
|
||||||
}
|
0,
|
||||||
|
uintptr(family),
|
||||||
pid := readNativeUint32(row[s.pid : s.pid+4])
|
1, // UDP_TABLE_OWNER_PID
|
||||||
return pid, nil
|
0,
|
||||||
}
|
)
|
||||||
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:
|
default:
|
||||||
return nil, fmt.Errorf("syscall error: %d", err)
|
return 0, errors.New("unsupported network")
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func readNativeUint32(b []byte) uint32 {
|
switch ret {
|
||||||
return *(*uint32)(unsafe.Pointer(&b[0]))
|
case 0:
|
||||||
|
buf = buf[:bufSize]
|
||||||
|
|
||||||
|
break loop
|
||||||
|
case uintptr(windows.ERROR_INSUFFICIENT_BUFFER):
|
||||||
|
pool.Put(buf)
|
||||||
|
buf = pool.Get(int(bufSize))
|
||||||
|
|
||||||
|
continue loop
|
||||||
|
default:
|
||||||
|
return 0, fmt.Errorf("syscall error: %d", ret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(buf) < int(unsafe.Sizeof(uint32(0))) {
|
||||||
|
return 0, fmt.Errorf("invalid table size: %d", len(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
entriesSize := *(*uint32)(unsafe.Pointer(&buf[0]))
|
||||||
|
|
||||||
|
switch protocol {
|
||||||
|
case windows.IPPROTO_TCP:
|
||||||
|
if family == windows.AF_INET {
|
||||||
|
type MibTcpRowOwnerPid struct {
|
||||||
|
State uint32
|
||||||
|
LocalAddr [4]byte
|
||||||
|
LocalPort uint32
|
||||||
|
RemoteAddr [4]byte
|
||||||
|
RemotePort uint32
|
||||||
|
OwningPid uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
if uint32(len(buf))-4 < entriesSize*uint32(unsafe.Sizeof(MibTcpRowOwnerPid{})) {
|
||||||
|
return 0, fmt.Errorf("invalid tables size: %d", len(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
entries := unsafe.Slice((*MibTcpRowOwnerPid)(unsafe.Pointer(&buf[4])), entriesSize)
|
||||||
|
for _, entry := range entries {
|
||||||
|
localAddr := netip.AddrFrom4(entry.LocalAddr)
|
||||||
|
localPort := windows.Ntohs(uint16(entry.LocalPort))
|
||||||
|
remoteAddr := netip.AddrFrom4(entry.RemoteAddr)
|
||||||
|
remotePort := windows.Ntohs(uint16(entry.RemotePort))
|
||||||
|
|
||||||
|
if localAddr == from.Addr() && remoteAddr == to.Addr() && localPort == from.Port() && remotePort == to.Port() {
|
||||||
|
return entry.OwningPid, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
type MibTcp6RowOwnerPid struct {
|
||||||
|
LocalAddr [16]byte
|
||||||
|
LocalScopeID uint32
|
||||||
|
LocalPort uint32
|
||||||
|
RemoteAddr [16]byte
|
||||||
|
RemoteScopeID uint32
|
||||||
|
RemotePort uint32
|
||||||
|
State uint32
|
||||||
|
OwningPid uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
if uint32(len(buf))-4 < entriesSize*uint32(unsafe.Sizeof(MibTcp6RowOwnerPid{})) {
|
||||||
|
return 0, fmt.Errorf("invalid tables size: %d", len(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
entries := unsafe.Slice((*MibTcp6RowOwnerPid)(unsafe.Pointer(&buf[4])), entriesSize)
|
||||||
|
for _, entry := range entries {
|
||||||
|
localAddr := netip.AddrFrom16(entry.LocalAddr)
|
||||||
|
localPort := windows.Ntohs(uint16(entry.LocalPort))
|
||||||
|
remoteAddr := netip.AddrFrom16(entry.RemoteAddr)
|
||||||
|
remotePort := windows.Ntohs(uint16(entry.RemotePort))
|
||||||
|
|
||||||
|
if localAddr == from.Addr() && remoteAddr == to.Addr() && localPort == from.Port() && remotePort == to.Port() {
|
||||||
|
return entry.OwningPid, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case windows.IPPROTO_UDP:
|
||||||
|
if family == windows.AF_INET {
|
||||||
|
type MibUdpRowOwnerPid struct {
|
||||||
|
LocalAddr [4]byte
|
||||||
|
LocalPort uint32
|
||||||
|
OwningPid uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
if uint32(len(buf))-4 < entriesSize*uint32(unsafe.Sizeof(MibUdpRowOwnerPid{})) {
|
||||||
|
return 0, fmt.Errorf("invalid tables size: %d", len(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
entries := unsafe.Slice((*MibUdpRowOwnerPid)(unsafe.Pointer(&buf[4])), entriesSize)
|
||||||
|
for _, entry := range entries {
|
||||||
|
localAddr := netip.AddrFrom4(entry.LocalAddr)
|
||||||
|
localPort := windows.Ntohs(uint16(entry.LocalPort))
|
||||||
|
|
||||||
|
if (localAddr == from.Addr() || localAddr.IsUnspecified()) && localPort == from.Port() {
|
||||||
|
return entry.OwningPid, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
type MibUdp6RowOwnerPid struct {
|
||||||
|
LocalAddr [16]byte
|
||||||
|
LocalScopeId uint32
|
||||||
|
LocalPort uint32
|
||||||
|
OwningPid uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
if uint32(len(buf))-4 < entriesSize*uint32(unsafe.Sizeof(MibUdp6RowOwnerPid{})) {
|
||||||
|
return 0, fmt.Errorf("invalid tables size: %d", len(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
entries := unsafe.Slice((*MibUdp6RowOwnerPid)(unsafe.Pointer(&buf[4])), entriesSize)
|
||||||
|
for _, entry := range entries {
|
||||||
|
localAddr := netip.AddrFrom16(entry.LocalAddr)
|
||||||
|
localPort := windows.Ntohs(uint16(entry.LocalPort))
|
||||||
|
|
||||||
|
if (localAddr == from.Addr() || localAddr.IsUnspecified()) && localPort == from.Port() {
|
||||||
|
return entry.OwningPid, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return 0, ErrInvalidNetwork
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, ErrNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExecPathFromPID(pid uint32) (string, error) {
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
@ -208,17 +217,13 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
}
|
}
|
||||||
defer windows.CloseHandle(h)
|
defer windows.CloseHandle(h)
|
||||||
|
|
||||||
buf := make([]uint16, syscall.MAX_LONG_PATH)
|
buf := make([]uint16, windows.MAX_LONG_PATH)
|
||||||
size := uint32(len(buf))
|
size := uint32(len(buf))
|
||||||
r1, _, err := syscall.Syscall6(
|
|
||||||
queryProcName, 4,
|
err = windows.QueryFullProcessImageName(h, 0, &buf[0], &size)
|
||||||
uintptr(h),
|
if err != nil {
|
||||||
uintptr(1),
|
|
||||||
uintptr(unsafe.Pointer(&buf[0])),
|
|
||||||
uintptr(unsafe.Pointer(&size)),
|
|
||||||
0, 0)
|
|
||||||
if r1 == 0 {
|
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return filepath.Base(syscall.UTF16ToString(buf[:size])), nil
|
|
||||||
|
return windows.UTF16ToString(buf[:size]), nil
|
||||||
}
|
}
|
||||||
|
12
component/resolver/defaults.go
Normal file
12
component/resolver/defaults.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||||
|
|
||||||
|
package resolver
|
||||||
|
|
||||||
|
import _ "unsafe"
|
||||||
|
|
||||||
|
//go:linkname defaultNS net.defaultNS
|
||||||
|
var defaultNS []string
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
defaultNS = []string{"114.114.114.114:53", "8.8.8.8:53"}
|
||||||
|
}
|
@ -3,12 +3,15 @@ package resolver
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
|
||||||
|
"github.com/miekg/dns"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -33,29 +36,33 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Resolver interface {
|
type Resolver interface {
|
||||||
|
LookupIP(ctx context.Context, host string) ([]net.IP, error)
|
||||||
|
LookupIPv4(ctx context.Context, host string) ([]net.IP, error)
|
||||||
|
LookupIPv6(ctx context.Context, host string) ([]net.IP, error)
|
||||||
ResolveIP(host string) (ip net.IP, err error)
|
ResolveIP(host string) (ip net.IP, err error)
|
||||||
ResolveIPv4(host string) (ip net.IP, err error)
|
ResolveIPv4(host string) (ip net.IP, err error)
|
||||||
ResolveIPv6(host string) (ip net.IP, err error)
|
ResolveIPv6(host string) (ip net.IP, err error)
|
||||||
|
ExchangeContext(ctx context.Context, m *dns.Msg) (msg *dns.Msg, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv4 with a host, return ipv4
|
// LookupIPv4 with a host, return ipv4 list
|
||||||
func ResolveIPv4(host string) (net.IP, error) {
|
func LookupIPv4(ctx context.Context, host string) ([]net.IP, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
if ip := node.Data.(net.IP).To4(); ip != nil {
|
if ip := node.Data.(net.IP).To4(); ip != nil {
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
if ip != nil {
|
if ip != nil {
|
||||||
if !strings.Contains(host, ":") {
|
if !strings.Contains(host, ":") {
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
return nil, ErrIPVersion
|
return nil, ErrIPVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
if DefaultResolver != nil {
|
if DefaultResolver != nil {
|
||||||
return DefaultResolver.ResolveIPv4(host)
|
return DefaultResolver.LookupIPv4(ctx, host)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
@ -67,31 +74,42 @@ func ResolveIPv4(host string) (net.IP, error) {
|
|||||||
return nil, ErrIPNotFound
|
return nil, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return ipAddrs[rand.Intn(len(ipAddrs))], nil
|
return ipAddrs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv6 with a host, return ipv6
|
// ResolveIPv4 with a host, return ipv4
|
||||||
func ResolveIPv6(host string) (net.IP, error) {
|
func ResolveIPv4(host string) (net.IP, error) {
|
||||||
|
ips, err := LookupIPv4(context.Background(), host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if len(ips) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
|
}
|
||||||
|
return ips[rand.Intn(len(ips))], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupIPv6 with a host, return ipv6 list
|
||||||
|
func LookupIPv6(ctx context.Context, host string) ([]net.IP, error) {
|
||||||
if DisableIPv6 {
|
if DisableIPv6 {
|
||||||
return nil, ErrIPv6Disabled
|
return nil, ErrIPv6Disabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
if ip := node.Data.(net.IP).To16(); ip != nil {
|
if ip := node.Data.(net.IP).To16(); ip != nil {
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
if ip != nil {
|
if ip != nil {
|
||||||
if strings.Contains(host, ":") {
|
if strings.Contains(host, ":") {
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
return nil, ErrIPVersion
|
return nil, ErrIPVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
if DefaultResolver != nil {
|
if DefaultResolver != nil {
|
||||||
return DefaultResolver.ResolveIPv6(host)
|
return DefaultResolver.LookupIPv6(ctx, host)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
@ -103,38 +121,62 @@ func ResolveIPv6(host string) (net.IP, error) {
|
|||||||
return nil, ErrIPNotFound
|
return nil, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return ipAddrs[rand.Intn(len(ipAddrs))], nil
|
return ipAddrs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
// ResolveIPv6 with a host, return ipv6
|
||||||
func ResolveIPWithResolver(host string, r Resolver) (net.IP, error) {
|
func ResolveIPv6(host string) (net.IP, error) {
|
||||||
|
ips, err := LookupIPv6(context.Background(), host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if len(ips) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
|
}
|
||||||
|
return ips[rand.Intn(len(ips))], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupIPWithResolver same as ResolveIP, but with a resolver
|
||||||
|
func LookupIPWithResolver(ctx context.Context, host string, r Resolver) ([]net.IP, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
return node.Data.(net.IP), nil
|
return []net.IP{node.Data.(net.IP)}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if r != nil {
|
if r != nil {
|
||||||
if DisableIPv6 {
|
if DisableIPv6 {
|
||||||
return r.ResolveIPv4(host)
|
return r.LookupIPv4(ctx, host)
|
||||||
}
|
}
|
||||||
return r.ResolveIP(host)
|
return r.LookupIP(ctx, host)
|
||||||
} else if DisableIPv6 {
|
} else if DisableIPv6 {
|
||||||
return ResolveIPv4(host)
|
return LookupIPv4(ctx, host)
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
if ip != nil {
|
if ip != nil {
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if len(ips) == 0 {
|
||||||
|
return nil, ErrIPNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
return ipAddr.IP, nil
|
return ips, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIP with a host, return ip
|
||||||
|
func LookupIP(ctx context.Context, host string) ([]net.IP, error) {
|
||||||
|
return LookupIPWithResolver(ctx, host, DefaultResolver)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIP with a host, return ip
|
// ResolveIP with a host, return ip
|
||||||
func ResolveIP(host string) (net.IP, error) {
|
func ResolveIP(host string) (net.IP, error) {
|
||||||
return ResolveIPWithResolver(host, DefaultResolver)
|
ips, err := LookupIP(context.Background(), host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if len(ips) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
|
}
|
||||||
|
return ips[rand.Intn(len(ips))], nil
|
||||||
}
|
}
|
||||||
|
@ -51,7 +51,7 @@ func ValidAndSplitDomain(domain string) ([]string, bool) {
|
|||||||
// 3. subdomain.*.example.com
|
// 3. subdomain.*.example.com
|
||||||
// 4. .example.com
|
// 4. .example.com
|
||||||
// 5. +.example.com
|
// 5. +.example.com
|
||||||
func (t *DomainTrie) Insert(domain string, data interface{}) error {
|
func (t *DomainTrie) Insert(domain string, data any) error {
|
||||||
parts, valid := ValidAndSplitDomain(domain)
|
parts, valid := ValidAndSplitDomain(domain)
|
||||||
if !valid {
|
if !valid {
|
||||||
return ErrInvalidDomain
|
return ErrInvalidDomain
|
||||||
@ -68,7 +68,7 @@ func (t *DomainTrie) Insert(domain string, data interface{}) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *DomainTrie) insert(parts []string, data interface{}) {
|
func (t *DomainTrie) insert(parts []string, data any) {
|
||||||
node := t.root
|
node := t.root
|
||||||
// reverse storage domain part to save space
|
// reverse storage domain part to save space
|
||||||
for i := len(parts) - 1; i >= 0; i-- {
|
for i := len(parts) - 1; i >= 0; i-- {
|
||||||
@ -109,13 +109,13 @@ func (t *DomainTrie) search(node *Node, parts []string) *Node {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if c := node.getChild(parts[len(parts)-1]); c != nil {
|
if c := node.getChild(parts[len(parts)-1]); c != nil {
|
||||||
if n := t.search(c, parts[:len(parts)-1]); n != nil {
|
if n := t.search(c, parts[:len(parts)-1]); n != nil && n.Data != nil {
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if c := node.getChild(wildcard); c != nil {
|
if c := node.getChild(wildcard); c != nil {
|
||||||
if n := t.search(c, parts[:len(parts)-1]); n != nil {
|
if n := t.search(c, parts[:len(parts)-1]); n != nil && n.Data != nil {
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -97,3 +97,11 @@ func TestTrie_Boundary(t *testing.T) {
|
|||||||
assert.NotNil(t, tree.Insert("..dev", localIP))
|
assert.NotNil(t, tree.Insert("..dev", localIP))
|
||||||
assert.Nil(t, tree.Search("dev"))
|
assert.Nil(t, tree.Search("dev"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTrie_WildcardBoundary(t *testing.T) {
|
||||||
|
tree := New()
|
||||||
|
tree.Insert("+.*", localIP)
|
||||||
|
tree.Insert("stun.*.*.*", localIP)
|
||||||
|
|
||||||
|
assert.NotNil(t, tree.Search("example.com"))
|
||||||
|
}
|
||||||
|
@ -2,8 +2,8 @@ package trie
|
|||||||
|
|
||||||
// Node is the trie's node
|
// Node is the trie's node
|
||||||
type Node struct {
|
type Node struct {
|
||||||
Data interface{}
|
|
||||||
children map[string]*Node
|
children map[string]*Node
|
||||||
|
Data any
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Node) getChild(s string) *Node {
|
func (n *Node) getChild(s string) *Node {
|
||||||
@ -18,7 +18,7 @@ func (n *Node) addChild(s string, child *Node) {
|
|||||||
n.children[s] = child
|
n.children[s] = child
|
||||||
}
|
}
|
||||||
|
|
||||||
func newNode(data interface{}) *Node {
|
func newNode(data any) *Node {
|
||||||
return &Node{
|
return &Node{
|
||||||
Data: data,
|
Data: data,
|
||||||
children: map[string]*Node{},
|
children: map[string]*Node{},
|
||||||
|
116
config/config.go
116
config/config.go
@ -22,7 +22,8 @@ import (
|
|||||||
R "github.com/Dreamacro/clash/rule"
|
R "github.com/Dreamacro/clash/rule"
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
"github.com/samber/lo"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// General config
|
// General config
|
||||||
@ -33,6 +34,7 @@ type General struct {
|
|||||||
LogLevel log.LogLevel `json:"log-level"`
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
IPv6 bool `json:"ipv6"`
|
IPv6 bool `json:"ipv6"`
|
||||||
Interface string `json:"-"`
|
Interface string `json:"-"`
|
||||||
|
RoutingMark int `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inbound
|
// Inbound
|
||||||
@ -67,6 +69,7 @@ type DNS struct {
|
|||||||
FakeIPRange *fakeip.Pool
|
FakeIPRange *fakeip.Pool
|
||||||
Hosts *trie.DomainTrie
|
Hosts *trie.DomainTrie
|
||||||
NameServerPolicy map[string]dns.NameServer
|
NameServerPolicy map[string]dns.NameServer
|
||||||
|
SearchDomains []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// FallbackFilter config
|
// FallbackFilter config
|
||||||
@ -84,7 +87,9 @@ type Profile struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Experimental config
|
// Experimental config
|
||||||
type Experimental struct{}
|
type Experimental struct {
|
||||||
|
UDPFallbackMatch bool `yaml:"udp-fallback-match"`
|
||||||
|
}
|
||||||
|
|
||||||
// Config is clash config manager
|
// Config is clash config manager
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@ -97,6 +102,7 @@ type Config struct {
|
|||||||
Users []auth.AuthUser
|
Users []auth.AuthUser
|
||||||
Proxies map[string]C.Proxy
|
Proxies map[string]C.Proxy
|
||||||
Providers map[string]providerTypes.ProxyProvider
|
Providers map[string]providerTypes.ProxyProvider
|
||||||
|
Tunnels []Tunnel
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawDNS struct {
|
type RawDNS struct {
|
||||||
@ -112,6 +118,7 @@ type RawDNS struct {
|
|||||||
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
||||||
DefaultNameserver []string `yaml:"default-nameserver"`
|
DefaultNameserver []string `yaml:"default-nameserver"`
|
||||||
NameServerPolicy map[string]string `yaml:"nameserver-policy"`
|
NameServerPolicy map[string]string `yaml:"nameserver-policy"`
|
||||||
|
SearchDomains []string `yaml:"search-domains"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawFallbackFilter struct {
|
type RawFallbackFilter struct {
|
||||||
@ -121,6 +128,64 @@ type RawFallbackFilter struct {
|
|||||||
Domain []string `yaml:"domain"`
|
Domain []string `yaml:"domain"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type tunnel struct {
|
||||||
|
Network []string `yaml:"network"`
|
||||||
|
Address string `yaml:"address"`
|
||||||
|
Target string `yaml:"target"`
|
||||||
|
Proxy string `yaml:"proxy"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Tunnel tunnel
|
||||||
|
|
||||||
|
// UnmarshalYAML implements yaml.Unmarshaler
|
||||||
|
func (t *Tunnel) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var tp string
|
||||||
|
if err := unmarshal(&tp); err != nil {
|
||||||
|
var inner tunnel
|
||||||
|
if err := unmarshal(&inner); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*t = Tunnel(inner)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse udp/tcp,address,target,proxy
|
||||||
|
parts := lo.Map(strings.Split(tp, ","), func(s string, _ int) string {
|
||||||
|
return strings.TrimSpace(s)
|
||||||
|
})
|
||||||
|
if len(parts) != 4 {
|
||||||
|
return fmt.Errorf("invalid tunnel config %s", tp)
|
||||||
|
}
|
||||||
|
network := strings.Split(parts[0], "/")
|
||||||
|
|
||||||
|
// validate network
|
||||||
|
for _, n := range network {
|
||||||
|
switch n {
|
||||||
|
case "tcp", "udp":
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("invalid tunnel network %s", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate address and target
|
||||||
|
address := parts[1]
|
||||||
|
target := parts[2]
|
||||||
|
for _, addr := range []string{address, target} {
|
||||||
|
if _, _, err := net.SplitHostPort(addr); err != nil {
|
||||||
|
return fmt.Errorf("invalid tunnel target or address %s", addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*t = Tunnel(tunnel{
|
||||||
|
Network: network,
|
||||||
|
Address: address,
|
||||||
|
Target: target,
|
||||||
|
Proxy: parts[3],
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type RawConfig struct {
|
type RawConfig struct {
|
||||||
Port int `yaml:"port"`
|
Port int `yaml:"port"`
|
||||||
SocksPort int `yaml:"socks-port"`
|
SocksPort int `yaml:"socks-port"`
|
||||||
@ -137,14 +202,16 @@ type RawConfig struct {
|
|||||||
ExternalUI string `yaml:"external-ui"`
|
ExternalUI string `yaml:"external-ui"`
|
||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
Interface string `yaml:"interface-name"`
|
Interface string `yaml:"interface-name"`
|
||||||
|
RoutingMark int `yaml:"routing-mark"`
|
||||||
|
Tunnels []Tunnel `yaml:"tunnels"`
|
||||||
|
|
||||||
ProxyProvider map[string]map[string]interface{} `yaml:"proxy-providers"`
|
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
||||||
Hosts map[string]string `yaml:"hosts"`
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
DNS RawDNS `yaml:"dns"`
|
DNS RawDNS `yaml:"dns"`
|
||||||
Experimental Experimental `yaml:"experimental"`
|
Experimental Experimental `yaml:"experimental"`
|
||||||
Profile Profile `yaml:"profile"`
|
Profile Profile `yaml:"profile"`
|
||||||
Proxy []map[string]interface{} `yaml:"proxies"`
|
Proxy []map[string]any `yaml:"proxies"`
|
||||||
ProxyGroup []map[string]interface{} `yaml:"proxy-groups"`
|
ProxyGroup []map[string]any `yaml:"proxy-groups"`
|
||||||
Rule []string `yaml:"rules"`
|
Rule []string `yaml:"rules"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -168,8 +235,8 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
LogLevel: log.INFO,
|
LogLevel: log.INFO,
|
||||||
Hosts: map[string]string{},
|
Hosts: map[string]string{},
|
||||||
Rule: []string{},
|
Rule: []string{},
|
||||||
Proxy: []map[string]interface{}{},
|
Proxy: []map[string]any{},
|
||||||
ProxyGroup: []map[string]interface{}{},
|
ProxyGroup: []map[string]any{},
|
||||||
DNS: RawDNS{
|
DNS: RawDNS{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
UseHosts: true,
|
UseHosts: true,
|
||||||
@ -235,6 +302,14 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
|
|
||||||
config.Users = parseAuthentication(rawCfg.Authentication)
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
|
config.Tunnels = rawCfg.Tunnels
|
||||||
|
// verify tunnels
|
||||||
|
for _, t := range config.Tunnels {
|
||||||
|
if _, ok := config.Proxies[t.Proxy]; !ok {
|
||||||
|
return nil, fmt.Errorf("tunnel proxy %s not found", t.Proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -269,6 +344,7 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
LogLevel: cfg.LogLevel,
|
LogLevel: cfg.LogLevel,
|
||||||
IPv6: cfg.IPv6,
|
IPv6: cfg.IPv6,
|
||||||
Interface: cfg.Interface,
|
Interface: cfg.Interface,
|
||||||
|
RoutingMark: cfg.RoutingMark,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -474,6 +550,10 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parse with specific interface
|
||||||
|
// .e.g 10.0.0.1#en0
|
||||||
|
interfaceName := u.Fragment
|
||||||
|
|
||||||
var addr, dnsNetType string
|
var addr, dnsNetType string
|
||||||
switch u.Scheme {
|
switch u.Scheme {
|
||||||
case "udp":
|
case "udp":
|
||||||
@ -486,7 +566,7 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
addr, err = hostWithDefaultPort(u.Host, "853")
|
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||||
dnsNetType = "tcp-tls" // DNS over TLS
|
dnsNetType = "tcp-tls" // DNS over TLS
|
||||||
case "https":
|
case "https":
|
||||||
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path}
|
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path, User: u.User}
|
||||||
addr = clearURL.String()
|
addr = clearURL.String()
|
||||||
dnsNetType = "https" // DNS over HTTPS
|
dnsNetType = "https" // DNS over HTTPS
|
||||||
case "dhcp":
|
case "dhcp":
|
||||||
@ -505,6 +585,7 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
dns.NameServer{
|
dns.NameServer{
|
||||||
Net: dnsNetType,
|
Net: dnsNetType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
|
Interface: interfaceName,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -623,15 +704,26 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie) (*DNS, error) {
|
|||||||
dnsCfg.Hosts = hosts
|
dnsCfg.Hosts = hosts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(cfg.SearchDomains) != 0 {
|
||||||
|
for _, domain := range cfg.SearchDomains {
|
||||||
|
if strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") {
|
||||||
|
return nil, errors.New("search domains should not start or end with '.'")
|
||||||
|
}
|
||||||
|
if strings.Contains(domain, ":") {
|
||||||
|
return nil, errors.New("search domains are for ipv4 only and should not contain ports")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dnsCfg.SearchDomains = cfg.SearchDomains
|
||||||
|
}
|
||||||
|
|
||||||
return dnsCfg, nil
|
return dnsCfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
||||||
users := make([]auth.AuthUser, 0)
|
users := []auth.AuthUser{}
|
||||||
for _, line := range rawRecords {
|
for _, line := range rawRecords {
|
||||||
userData := strings.SplitN(line, ":", 2)
|
if user, pass, found := strings.Cut(line, ":"); found {
|
||||||
if len(userData) == 2 {
|
users = append(users, auth.AuthUser{User: user, Pass: pass})
|
||||||
users = append(users, auth.AuthUser{User: userData[0], Pass: userData[1]})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return users
|
return users
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user