Compare commits
423 Commits
v1.2.0_tun
...
v6.0.1
Author | SHA1 | Date | |
---|---|---|---|
4323eb79f3 | |||
2c7ae8753d | |||
8438cade99 | |||
9cc14b80b9 | |||
85410e1f25 | |||
6fce893428 | |||
2dd7a87f4c | |||
c6d1b7aff4 | |||
dc0dc1cfe1 | |||
e0bec5ad2b | |||
d7e63975b9 | |||
394a297368 | |||
10a9eab542 | |||
368a44ff73 | |||
4209aa6738 | |||
e22053ce2c | |||
9d8cd036ff | |||
2aad9818e8 | |||
4d5c0d2bf4 | |||
861205dbbe | |||
9dbe20f2c5 | |||
8dea62cd63 | |||
2d99f86780 | |||
fac63625fc | |||
b9f270162a | |||
bbbe371ea9 | |||
e2409f9639 | |||
4f634edaa9 | |||
f1dab9e9ce | |||
8217db82ce | |||
f9dd0a6bfc | |||
b9b25be68d | |||
179e5aad58 | |||
fc1eaf9a9d | |||
1756730693 | |||
c7bc67e44c | |||
949c1551f8 | |||
b23a333acf | |||
47568051bf | |||
22c1e05e1c | |||
c161d5e6be | |||
573be855f7 | |||
a38b2bcb6d | |||
2e74986fe4 | |||
30eaa8add6 | |||
b498d2dda2 | |||
96a32f5038 | |||
e11f6f84df | |||
5a1e1050b7 | |||
73aa8c7be7 | |||
183973e823 | |||
2e08a4b4e1 | |||
564a6fdf35 | |||
cca3a1a934 | |||
ffb49ba4c5 | |||
e4fb10faf9 | |||
16a35527b7 | |||
4fd7d0f707 | |||
dee1aeb6c3 | |||
2f95d56a12 | |||
c77993eed3 | |||
ce663a7b96 | |||
9c2ca0feb0 | |||
b8d5321615 | |||
eb6f7e3158 | |||
0947cb4a5a | |||
0368bb4180 | |||
4aeac0e227 | |||
bd3c493c9f | |||
0a99fc4d74 | |||
19fc70b2c4 | |||
81b5543b0d | |||
2e1d9a4f2e | |||
de4341c8cd | |||
8a85c63b08 | |||
b0dd74e74e | |||
4dd9e199b7 | |||
3d6aea4c1e | |||
0cb5270452 | |||
3f6d2e5f91 | |||
3b16fcef92 | |||
f91d106cdf | |||
9e6ba64940 | |||
bee1bddceb | |||
e98dcc4267 | |||
4b79f8de93 | |||
f40c2eb71d | |||
7ca1a03d73 | |||
6c4791480e | |||
42d853a7e6 | |||
5d36d8b139 | |||
5a4441c47f | |||
0ca10798ea | |||
3ea3653d7a | |||
58cd8f9ac1 | |||
ea0d236259 | |||
48a01adb7a | |||
f8d7f29856 | |||
1cf9321aa0 | |||
71a1f5dfbd | |||
25426cba33 | |||
9d364f66e9 | |||
7c23fa2bd4 | |||
0658ecadd3 | |||
efbc334b3b | |||
80764217c2 | |||
45fe6e996b | |||
36a719e2f8 | |||
1b6b0052c2 | |||
c981ef0f28 | |||
1bf291d240 | |||
b179d09efb | |||
4be17653e0 | |||
21446ba5d4 | |||
75ce6b59bf | |||
ce96ac35fb | |||
173e10abe6 | |||
a6eb11ce18 | |||
0c65f6962a | |||
baa9e02af6 | |||
673541e2a8 | |||
14878b37f6 | |||
83e0abaa8c | |||
7166db2ac9 | |||
815a060309 | |||
544e0f137d | |||
07906c0aa5 | |||
b2981f921c | |||
7be3e617ab | |||
9a3bc8ef9e | |||
e083d1c57d | |||
ce4902e5e6 | |||
4b9edc3b66 | |||
91e48b707b | |||
5719b9d22f | |||
b553dd749b | |||
9461bcd44e | |||
6548dc90fa | |||
908ca20afa | |||
88e4b3575e | |||
559b3ff9f3 | |||
127634028d | |||
81c5a65f23 | |||
591ee119c2 | |||
5b03cc56e7 | |||
c4216218c8 | |||
63840b3358 | |||
045dd0589b | |||
705311b70e | |||
55ce40fbd1 | |||
07fda93111 | |||
012e044c54 | |||
b323315583 | |||
4c10d6e212 | |||
ece3bb360a | |||
5a7b9bdf45 | |||
028ecb70c5 | |||
4e0b22f42d | |||
dbd27ef910 | |||
ffff1418f2 | |||
64a5fd02da | |||
611ce5f5f1 | |||
0a0b8074f4 | |||
f66c3b6f86 | |||
a3d49d1ed4 | |||
0d068e7b5f | |||
24583009c4 | |||
a593d68c42 | |||
520657e953 | |||
6c64164bee | |||
9b4ddbed2c | |||
79d984ee8e | |||
7a54d616c4 | |||
f19b67fe9d | |||
91e83ea955 | |||
a375b85fa0 | |||
4cc661920e | |||
b5f6f26de4 | |||
e068563b58 | |||
bf6839e5f3 | |||
e0040b7e5d | |||
3beb71b6e1 | |||
668d29d91f | |||
5386c3903d | |||
6a4d2b3368 | |||
d9d8507c8f | |||
5b7f46bc97 | |||
d1838f663e | |||
2d1c031ce0 | |||
e67f94b87a | |||
2df890c4ee | |||
520256365e | |||
9270d3c475 | |||
c8b1050c15 | |||
39de5d58c8 | |||
a38f30ec3b | |||
2ea92d70f9 | |||
ea2e715da9 | |||
1350330fe0 | |||
317797acc8 | |||
8766764d49 | |||
b8d48e1618 | |||
f972d1fa58 | |||
df78ba8fa6 | |||
0c83575302 | |||
e9151bc43f | |||
68345b6a19 | |||
435bee0ca2 | |||
92d169ca81 | |||
30f1b29257 | |||
c503e44324 | |||
ce509295c0 | |||
f671d6a1fd | |||
e194efcecb | |||
609d69191a | |||
c791044ddf | |||
dc2abe6eeb | |||
1071e3f4a3 | |||
acc249495d | |||
5a2cc9a36f | |||
1cc6cfab9c | |||
0183d752a0 | |||
2f24e49ff6 | |||
016862f7a5 | |||
c3df768f79 | |||
0f2123179a | |||
1034780e8e | |||
f01ac69654 | |||
c85305ead8 | |||
3e89bee524 | |||
68fccfacc0 | |||
cf52fbed65 | |||
a924819fbf | |||
13c82754ff | |||
002163f07b | |||
9c5b184db6 | |||
3ab784dd80 | |||
f1c4d85eb3 | |||
b9fc393f95 | |||
557347d366 | |||
a7f3b85200 | |||
7550067fde | |||
076a0840bf | |||
5ebcc526de | |||
3772ad8ddb | |||
5ad7237fa7 | |||
49e25f502f | |||
06942c67fd | |||
9259c9f3ff | |||
37cf166d14 | |||
27292dac0c | |||
847c91503b | |||
ca8ed0a01b | |||
46dc262e8e | |||
7465eaafa1 | |||
d70cfefde7 | |||
52c37f7140 | |||
180bce2940 | |||
4a446c4e31 | |||
d7f5e8d3de | |||
0a180eeb40 | |||
7ff48ea42d | |||
a0e44f4041 | |||
2f6f9ebc2e | |||
28a1475f66 | |||
c28f42d823 | |||
2bf34c766e | |||
35b19c3d7f | |||
90e6ed4612 | |||
ae5a790510 | |||
3b277aa8ec | |||
176eb3926b | |||
776728fb30 | |||
a732e1a603 | |||
1cdaf782ba | |||
f1157d0a09 | |||
f376409041 | |||
45b3afdd33 | |||
875fdb3a5b | |||
25e115d042 | |||
d633e3d96e | |||
6e9d837a7d | |||
63b9d66365 | |||
be0fadc09e | |||
76dccebbf6 | |||
cd5b735973 | |||
9e4e1482d9 | |||
9974fba56e | |||
4bd5764c4e | |||
deeab8b45f | |||
af30664c51 | |||
6962f0b7e1 | |||
6e5859d1bf | |||
87ca93b979 | |||
11052d8f77 | |||
a5ce62db33 | |||
2f8e575308 | |||
62b70725ef | |||
8595d6c2e9 | |||
03b956b7a3 | |||
e5c99cbee7 | |||
58a47e1835 | |||
daf83eb6f7 | |||
bb68b59c9a | |||
c3cfa3d6cd | |||
b15344ec78 | |||
56c38890f9 | |||
daae846db3 | |||
ee6c1871a9 | |||
00e44cd141 | |||
4ab986cccb | |||
64869d0f17 | |||
7f0368da66 | |||
4f1b227ca2 | |||
16abba385a | |||
75b5f633cd | |||
8ae68552a6 | |||
d35d6c9ac9 | |||
a832cfdb65 | |||
951a5a0eb5 | |||
89609cc4a2 | |||
bfb976bbdc | |||
a15d2535f1 | |||
610c79570a | |||
051c81518c | |||
0209efd423 | |||
ba6fdd2962 | |||
c14dd79e69 | |||
9475799615 | |||
14917c8af1 | |||
3bb32d12e0 | |||
013b839678 | |||
a06382cebc | |||
ebc3f36236 | |||
e2a0437685 | |||
82c8e02d02 | |||
a210ec4197 | |||
0b72395704 | |||
8955107d6b | |||
69aef9cec0 | |||
9e44e21406 | |||
b0fdd8dc47 | |||
e92ef587bb | |||
5657aa50cf | |||
7d17d53a8f | |||
58ef4ddbba | |||
a78b89d16e | |||
833b43a538 | |||
8df3efe932 | |||
645c3154d6 | |||
a847d7b58d | |||
37ea8aff5c | |||
cb4ce8be6a | |||
a85395e777 | |||
819b29956b | |||
eb999b3bf1 | |||
8580ee8898 | |||
58552447ef | |||
23ca356447 | |||
fae65b97ec | |||
99f0231a9b | |||
edf1bb476d | |||
5c53243e81 | |||
b99b4ad15f | |||
6369921364 | |||
c6f923041f | |||
53eb3f15bb | |||
b15a7c8b6f | |||
038f973f90 | |||
bf6bfdd930 | |||
0431969a73 | |||
c7b257b188 | |||
885f69b81d | |||
cb52682790 | |||
c65835d9e4 | |||
92bb026f70 | |||
c22c7efd07 | |||
e4b30dacd4 | |||
353ae30839 | |||
828ff82ff2 | |||
35cf39e415 | |||
340efef2d8 | |||
796eb5c95c | |||
0f2b87497b | |||
06e9243fda | |||
d4cc650633 | |||
14af94205c | |||
078389f4f6 | |||
cad18b7529 | |||
aeddc8eb1d | |||
f7393509a3 | |||
8e641a4e31 | |||
223de1f3fd | |||
1fb2bc07d7 | |||
eb57d246cf | |||
0001a1b844 | |||
b20e202321 | |||
900e852525 | |||
1f3968bd50 | |||
5d510eb5aa | |||
3d246d5150 | |||
3686446919 | |||
a412745314 | |||
d0c23998d2 | |||
038cc1f6b5 | |||
6bd186d3c0 | |||
4c6bb7178b | |||
cec14db4a8 | |||
53287d597b | |||
964bbe1957 | |||
c824ace2d7 | |||
78cef7df59 | |||
62b3ebe49f | |||
ff420ed2ee | |||
d1568325e6 | |||
5a27df899f | |||
ab12b440aa | |||
4b614090f8 | |||
63d07db4bf | |||
cbea46b0c8 | |||
c0e9d69163 | |||
d29d824da8 | |||
862174d21b |
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,76 +0,0 @@
|
|||||||
name: Bug report
|
|
||||||
description: Create a report to help us improve
|
|
||||||
title: "[Bug] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
如果你可以自己 debug 并解决的话,提交 PR 吧
|
|
||||||
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
|
||||||
I have searched on the [issue tracker](……/) for a related issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经使用 dev 分支版本测试过,问题依旧存在
|
|
||||||
I have tested using the dev branch, and the issue still exists.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
|
||||||
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
attributes:
|
|
||||||
label: Clash version
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: os
|
|
||||||
attributes:
|
|
||||||
label: What OS are you seeing the problem on?
|
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- macOS
|
|
||||||
- Windows
|
|
||||||
- Linux
|
|
||||||
- OpenBSD/FreeBSD
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: yaml
|
|
||||||
label: "Clash config"
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash core 脱敏后配置文件的内容
|
|
||||||
Paste the Clash core configuration below.
|
|
||||||
"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: shell
|
|
||||||
label: Clash log
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
|
||||||
"
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
validations:
|
|
||||||
required: true
|
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
6
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -1,6 +0,0 @@
|
|||||||
blank_issues_enabled: false
|
|
||||||
|
|
||||||
contact_links:
|
|
||||||
- name: Get help in GitHub Discussions
|
|
||||||
url: https://github.com/Dreamacro/clash/discussions
|
|
||||||
about: Have a question? Not sure if your issue affects everyone reproducibly? The quickest way to get help is on Clash's GitHub Discussions!
|
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,36 +0,0 @@
|
|||||||
name: Feature request
|
|
||||||
description: Suggest an idea for this project
|
|
||||||
title: "[Feature] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
|
||||||
I have searched on the [issue tracker](……/) for a related feature request.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Possible Solution
|
|
||||||
description: "
|
|
||||||
此项非必须,但是如果你有想法的话欢迎提出。
|
|
||||||
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
|
||||||
"
|
|
20
.github/workflows/build.yaml
vendored
Normal file
20
.github/workflows/build.yaml
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
name: Build All
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v1
|
||||||
|
with:
|
||||||
|
go-version: 1.18
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v1
|
||||||
|
- name: Build
|
||||||
|
run: make all
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
29
.github/workflows/codeql-analysis.yml
vendored
29
.github/workflows/codeql-analysis.yml
vendored
@ -1,29 +0,0 @@
|
|||||||
name: CodeQL
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ rm ]
|
|
||||||
jobs:
|
|
||||||
analyze:
|
|
||||||
name: Analyze
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
language: ['go']
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Initialize CodeQL
|
|
||||||
uses: github/codeql-action/init@v1
|
|
||||||
with:
|
|
||||||
languages: ${{ matrix.language }}
|
|
||||||
|
|
||||||
- name: Autobuild
|
|
||||||
uses: github/codeql-action/autobuild@v1
|
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
|
||||||
uses: github/codeql-action/analyze@v1
|
|
63
.github/workflows/docker.yaml
vendored
Normal file
63
.github/workflows/docker.yaml
vendored
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
name: Docker
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- Beta
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: docker.io
|
||||||
|
IMAGE_NAME: '{{ env.DOCKERHUB_ACCOUNT }}/{{ env.DOCKERHUB_REPO }}'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v1
|
||||||
|
|
||||||
|
- name: Setup Docker buildx
|
||||||
|
uses: docker/setup-buildx-action@v1
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v3
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
|
- name: Log into registry ${{ env.REGISTRY }}
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@v1
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
|
# https://github.com/docker/build-push-action
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build-and-push
|
||||||
|
uses: docker/build-push-action@v2
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
platforms: |
|
||||||
|
linux/386
|
||||||
|
linux/amd64
|
||||||
|
linux/arm64/v8
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
79
.github/workflows/docker.yml
vendored
79
.github/workflows/docker.yml
vendored
@ -1,79 +0,0 @@
|
|||||||
name: Publish Docker Image
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- rm
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
build:
|
|
||||||
name: Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
with:
|
|
||||||
platforms: all
|
|
||||||
|
|
||||||
- name: Set up docker buildx
|
|
||||||
id: buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
- name: Login to DockerHub
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
|
||||||
|
|
||||||
- name: Login to Github Package
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: Dreamacro
|
|
||||||
password: ${{ secrets.PACKAGE_TOKEN }}
|
|
||||||
|
|
||||||
- name: Build dev branch and push
|
|
||||||
if: github.ref == 'refs/heads/dev'
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
|
||||||
push: true
|
|
||||||
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
|
|
||||||
- name: Get all docker tags
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
uses: actions/github-script@v6
|
|
||||||
id: tags
|
|
||||||
with:
|
|
||||||
script: |
|
|
||||||
const ref = context.payload.ref.replace(/\/?refs\/tags\//, '')
|
|
||||||
const tags = [
|
|
||||||
'dreamacro/clash:latest',
|
|
||||||
`dreamacro/clash:${ref}`,
|
|
||||||
'ghcr.io/dreamacro/clash:latest',
|
|
||||||
`ghcr.io/dreamacro/clash:${ref}`
|
|
||||||
]
|
|
||||||
return tags.join(',')
|
|
||||||
result-encoding: string
|
|
||||||
|
|
||||||
- name: Build release and push
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
|
||||||
push: true
|
|
||||||
tags: ${{steps.tags.outputs.result}}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
22
.github/workflows/linter.yml
vendored
22
.github/workflows/linter.yml
vendored
@ -1,22 +0,0 @@
|
|||||||
name: Linter
|
|
||||||
on: [push, pull_request]
|
|
||||||
jobs:
|
|
||||||
lint:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: golangci-lint
|
|
||||||
uses: golangci/golangci-lint-action@v3
|
|
||||||
with:
|
|
||||||
version: latest
|
|
67
.github/workflows/prerelease.yml
vendored
Normal file
67
.github/workflows/prerelease.yml
vendored
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
name: prerelease
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get latest go version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
- name: Test
|
||||||
|
if: ${{env.GITHUB_REF_NAME=='Beta'}}
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j releases
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: ${{ env.GITHUB_REF_NAME }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1
|
||||||
|
with:
|
||||||
|
tag_name: ${{env.GITHUB_REF_NAME}}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Upload Alpha
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag: ${{env.GITHUB_REF_NAME}}
|
||||||
|
tag_name: ${{env.GITHUB_REF_NAME}}
|
||||||
|
files: bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
44
.github/workflows/release.yaml
vendored
Normal file
44
.github/workflows/release.yaml
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
name: release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get latest go version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
- name: Test
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j releases
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
||||||
|
with:
|
||||||
|
tag: ${{ github.ref }}
|
||||||
|
files: bin/*
|
||||||
|
generate_release_notes: true
|
73
.github/workflows/release.yml
vendored
73
.github/workflows/release.yml
vendored
@ -1,73 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on: [push]
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Go cache paths
|
|
||||||
id: go-cache-paths
|
|
||||||
run: |
|
|
||||||
echo "::set-output name=go-build::$(go env GOCACHE)"
|
|
||||||
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
|
||||||
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
${{ steps.go-cache-paths.outputs.go-mod }}
|
|
||||||
${{ steps.go-cache-paths.outputs.go-build }}
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
- name: Get dependencies, run test
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
env:
|
|
||||||
NAME: clash
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j releases
|
|
||||||
|
|
||||||
#- name: Prepare upload
|
|
||||||
# run: |
|
|
||||||
# echo "FILE_DATE=_$(date +"%Y%m%d%H%M")" >> $GITHUB_ENV
|
|
||||||
# echo "FILE_SHA=$(git describe --tags --always 2>/dev/null)" >> $GITHUB_ENV
|
|
||||||
#
|
|
||||||
#- name: Upload files to Artifacts
|
|
||||||
# uses: actions/upload-artifact@v2
|
|
||||||
# if: startsWith(github.ref, 'refs/tags/') == false
|
|
||||||
# with:
|
|
||||||
# name: clash_${{ env.FILE_SHA }}${{ env.FILE_DATE }}
|
|
||||||
# path: |
|
|
||||||
# bin/*
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
|
|
||||||
#- name: Delete workflow runs
|
|
||||||
# uses: GitRML/delete-workflow-runs@main
|
|
||||||
# with:
|
|
||||||
# retain_days: 1
|
|
||||||
# keep_minimum_runs: 2
|
|
19
.github/workflows/stale.yml
vendored
19
.github/workflows/stale.yml
vendored
@ -1,19 +0,0 @@
|
|||||||
|
|
||||||
name: Mark stale issues and pull requests
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- rm
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
stale:
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/stale@v5
|
|
||||||
with:
|
|
||||||
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
|
|
||||||
days-before-stale: 60
|
|
||||||
days-before-close: 5
|
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -23,3 +23,5 @@ vendor
|
|||||||
|
|
||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
|
/output
|
||||||
|
/.vscode
|
30
Dockerfile
30
Dockerfile
@ -1,18 +1,28 @@
|
|||||||
FROM golang:alpine as builder
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
|
ARG TARGETOS
|
||||||
|
ARG TARGETARCH
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache make git && \
|
||||||
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
mkdir /clash-config && \
|
||||||
WORKDIR /clash-src
|
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||||
COPY --from=tonistiigi/xx:golang / /
|
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||||
|
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat \
|
||||||
|
|
||||||
COPY . /clash-src
|
COPY . /clash-src
|
||||||
RUN go mod download && \
|
WORKDIR /clash-src
|
||||||
make docker && \
|
RUN go mod download &&\
|
||||||
mv ./bin/clash-docker /clash
|
make docker &&\
|
||||||
|
mv ./bin/Clash.Meta-docker /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
|
||||||
COPY --from=builder /clash /
|
VOLUME ["/root/.config/clash/"]
|
||||||
ENTRYPOINT ["/clash"]
|
|
||||||
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
|
COPY --from=builder /clash /clash
|
||||||
|
RUN chmod +x /clash
|
||||||
|
ENTRYPOINT [ "/clash" ]
|
99
Makefile
99
Makefile
@ -1,63 +1,86 @@
|
|||||||
NAME=clash
|
NAME=Clash.Meta
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
VERSION=$(shell git describe --tags --always 2>/dev/null || echo "unknown version")
|
BRANCH=$(shell git rev-parse --abbrev-ref HEAD)
|
||||||
|
ifeq ($(BRANCH),Alpha)
|
||||||
|
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
||||||
|
else ifeq ($(BRANCH),Beta)
|
||||||
|
VERSION=beta-$(shell git rev-parse --short HEAD)
|
||||||
|
else ifeq ($(BRANCH),HEAD)
|
||||||
|
VERSION=$(shell git describe --tags)
|
||||||
|
else
|
||||||
|
VERSION=unknown
|
||||||
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64v1 \
|
||||||
darwin-amd64-v3 \
|
darwin-amd64v2 \
|
||||||
|
darwin-amd64v3 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-386 \
|
linux-amd64v1 \
|
||||||
linux-amd64 \
|
linux-amd64v2 \
|
||||||
linux-amd64-v3 \
|
linux-amd64v3 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
linux-armv8 \
|
linux-arm64 \
|
||||||
|
linux-mips64 \
|
||||||
|
linux-mips64le \
|
||||||
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 \
|
android-arm64 \
|
||||||
linux-mips64le \
|
|
||||||
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-amd64v1 \
|
||||||
windows-amd64-v3 \
|
windows-amd64v2 \
|
||||||
|
windows-amd64v3 \
|
||||||
windows-arm64 \
|
windows-arm64 \
|
||||||
windows-arm32v7
|
windows-arm32v7
|
||||||
|
|
||||||
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
all:linux-amd64 linux-arm64\
|
||||||
|
darwin-amd64 darwin-arm64\
|
||||||
|
windows-amd64 windows-arm64\
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64v3:
|
||||||
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-amd64-v3:
|
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64v2:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64v1:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64:
|
linux-amd64v3:
|
||||||
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-amd64-v3:
|
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64v2:
|
||||||
|
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64v1:
|
||||||
|
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-arm64:
|
||||||
|
GOARCH=arm64 GOOS=linux $(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)-$@
|
||||||
|
|
||||||
@ -67,9 +90,6 @@ 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:
|
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mips-softfloat:
|
linux-mips-softfloat:
|
||||||
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -88,13 +108,13 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
android-arm64:
|
||||||
|
GOARCH=arm64 GOOS=android $(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)-$@
|
|
||||||
|
|
||||||
freebsd-amd64-v3:
|
|
||||||
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-arm64:
|
freebsd-arm64:
|
||||||
@ -103,12 +123,15 @@ freebsd-arm64:
|
|||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64:
|
windows-amd64v3:
|
||||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
|
||||||
|
|
||||||
windows-amd64-v3:
|
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64v2:
|
||||||
|
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64v1:
|
||||||
|
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(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
|
||||||
|
|
||||||
@ -133,11 +156,7 @@ vet:
|
|||||||
go test ./...
|
go test ./...
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
GOOS=darwin golangci-lint run ./...
|
golangci-lint run ./...
|
||||||
GOOS=windows golangci-lint run ./...
|
|
||||||
GOOS=linux golangci-lint run ./...
|
|
||||||
GOOS=freebsd golangci-lint run ./...
|
|
||||||
GOOS=openbsd golangci-lint run ./...
|
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(BINDIR)/*
|
rm $(BINDIR)/*
|
||||||
|
425
README.md
425
README.md
@ -1,23 +1,20 @@
|
|||||||
<h1 align="center">
|
<h1 align="center">
|
||||||
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
<img src="Meta.png" alt="Meta Kennel" width="200">
|
||||||
<br>Clash<br>
|
<br>Meta Kernel<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h4 align="center">A rule-based tunnel in Go.</h4>
|
<h3 align="center">Another Clash Kernel.</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/Dreamacro/clash/actions">
|
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
||||||
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
||||||
</a>
|
|
||||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
|
||||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
|
||||||
</a>
|
</a>
|
||||||
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
||||||
<a href="https://github.com/Dreamacro/clash/releases">
|
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
||||||
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Dreamacro/clash/releases/tag/premium">
|
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
||||||
<img src="https://img.shields.io/badge/release-Premium-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@ -36,158 +33,85 @@
|
|||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
## Advanced usage for this branch
|
## Advanced usage for this branch
|
||||||
### General configuration
|
|
||||||
```yaml
|
|
||||||
sniffing: true # Sniff TLS SNI
|
|
||||||
|
|
||||||
force-cert-verify: true # force verify TLS Certificate, prevent machine-in-the-middle attacks
|
|
||||||
```
|
|
||||||
|
|
||||||
### MITM configuration
|
|
||||||
A root CA certificate is required, the
|
|
||||||
MITM proxy server will generate a CA certificate file and a CA private key file in your Clash home directory, you can use your own certificate replace it.
|
|
||||||
|
|
||||||
Need to install and trust the CA certificate on the client device, open this URL [http://mitm.clash/cert.crt](http://mitm.clash/cert.crt) by the web browser to install the CA certificate, the host name 'mitm.clash' was always been hijacked.
|
|
||||||
|
|
||||||
NOTE: this feature cannot work on tls pinning
|
|
||||||
|
|
||||||
WARNING: DO NOT USE THIS FEATURE TO BREAK LOCAL LAWS
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
# Port of MITM proxy server on the local end
|
|
||||||
mitm-port: 7894
|
|
||||||
|
|
||||||
# Man-In-The-Middle attack
|
|
||||||
mitm:
|
|
||||||
hosts: # use for others proxy type. E.g: TUN, socks
|
|
||||||
- +.example.com
|
|
||||||
rules: # rewrite rules
|
|
||||||
- '^https?://www\.example\.com/1 url reject' # The "reject" returns HTTP status code 404 with no content.
|
|
||||||
- '^https?://www\.example\.com/2 url reject-200' # The "reject-200" returns HTTP status code 200 with no content.
|
|
||||||
- '^https?://www\.example\.com/3 url reject-img' # The "reject-img" returns HTTP status code 200 with content of 1px png.
|
|
||||||
- '^https?://www\.example\.com/4 url reject-dict' # The "reject-dict" returns HTTP status code 200 with content of empty json object.
|
|
||||||
- '^https?://www\.example\.com/5 url reject-array' # The "reject-array" returns HTTP status code 200 with content of empty json array.
|
|
||||||
- '^https?://www\.example\.com/(6) url 302 https://www.example.com/new-$1'
|
|
||||||
- '^https?://www\.(example)\.com/7 url 307 https://www.$1.com/new-7'
|
|
||||||
- '^https?://www\.example\.com/8 url request-header (\r\n)User-Agent:.+(\r\n) request-header $1User-Agent: haha-wriohoh$2' # The "request-header" works for all the http headers not just one single header, so you can match two or more headers including CRLF in one regular expression.
|
|
||||||
- '^https?://www\.example\.com/9 url request-body "pos_2":\[.*\],"pos_3" request-body "pos_2":[{"xx": "xx"}],"pos_3"'
|
|
||||||
- '^https?://www\.example\.com/10 url response-header (\r\n)Tracecode:.+(\r\n) response-header $1Tracecode: 88888888888$2'
|
|
||||||
- '^https?://www\.example\.com/11 url response-body "errmsg":"ok" response-body "errmsg":"not-ok"'
|
|
||||||
```
|
|
||||||
|
|
||||||
### DNS configuration
|
### DNS configuration
|
||||||
Support resolve ip with a proxy tunnel or interface.
|
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
Use `curl -X POST controllerip:port/cache/fakeip/flush` to flush persistence fakeip
|
Restore `Redir remote resolution`.
|
||||||
```yaml
|
|
||||||
dns:
|
Support resolve ip with a `Proxy Tunnel`.
|
||||||
enable: true
|
|
||||||
use-hosts: true
|
```yaml
|
||||||
ipv6: false
|
proxy-groups:
|
||||||
enhanced-mode: fake-ip
|
|
||||||
fake-ip-range: 198.18.0.1/16
|
- name: DNS
|
||||||
listen: 127.0.0.1:6868
|
type: url-test
|
||||||
default-nameserver:
|
use:
|
||||||
- 119.29.29.29
|
- HK
|
||||||
- 114.114.114.114
|
url: http://cp.cloudflare.com
|
||||||
nameserver:
|
interval: 180
|
||||||
- https://doh.pub/dns-query
|
lazy: true
|
||||||
- tls://223.5.5.5:853
|
```
|
||||||
fallback:
|
```yaml
|
||||||
- 'tls://8.8.4.4:853#proxy or interface'
|
dns:
|
||||||
- 'https://1.0.0.1/dns-query#Proxy' # append the proxy adapter name to the end of DNS URL with '#' prefix.
|
enable: true
|
||||||
fallback-filter:
|
use-hosts: true
|
||||||
geoip: false
|
ipv6: false
|
||||||
geosite:
|
enhanced-mode: redir-host
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to untrusted DNS providers.
|
fake-ip-range: 198.18.0.1/16
|
||||||
domain:
|
listen: 127.0.0.1:6868
|
||||||
- +.example.com
|
default-nameserver:
|
||||||
ipcidr:
|
- 119.29.29.29
|
||||||
- 0.0.0.0/32
|
- 114.114.114.114
|
||||||
```
|
nameserver:
|
||||||
|
- https://doh.pub/dns-query
|
||||||
|
- tls://223.5.5.5:853
|
||||||
|
fallback:
|
||||||
|
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
||||||
|
- 'tls://8.8.4.4:853#DNS'
|
||||||
|
fallback-filter:
|
||||||
|
geoip: false
|
||||||
|
geosite:
|
||||||
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
||||||
|
domain:
|
||||||
|
- +.example.com
|
||||||
|
ipcidr:
|
||||||
|
- 0.0.0.0/32
|
||||||
|
```
|
||||||
|
|
||||||
### TUN configuration
|
### TUN configuration
|
||||||
Simply add the following to the main configuration:
|
|
||||||
|
|
||||||
#### NOTE:
|
Supports macOS, Linux and Windows.
|
||||||
> auto-route and auto-detect-interface only available on macOS, Windows and Linux, receive IPv4 traffic
|
|
||||||
|
Built-in [Wintun](https://www.wintun.net) driver.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
# Enable the TUN listener
|
||||||
tun:
|
tun:
|
||||||
enable: true
|
enable: true
|
||||||
stack: system # or gvisor
|
stack: gvisor # only gvisor
|
||||||
# device: tun://utun8 # or fd://xxx, it's optional
|
dns-hijack:
|
||||||
# dns-hijack:
|
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||||
# - 8.8.8.8:53
|
|
||||||
# - tcp://8.8.8.8:53
|
|
||||||
# - any:53
|
|
||||||
# - tcp://any:53
|
|
||||||
auto-route: true # auto set global route
|
|
||||||
auto-detect-interface: true # conflict with interface-name
|
|
||||||
```
|
|
||||||
or
|
|
||||||
```yaml
|
|
||||||
interface-name: en0
|
|
||||||
|
|
||||||
tun:
|
|
||||||
enable: true
|
|
||||||
stack: system # or gvisor
|
|
||||||
# dns-hijack:
|
|
||||||
# - 8.8.8.8:53
|
|
||||||
# - tcp://8.8.8.8:53
|
|
||||||
auto-route: true # auto set global route
|
auto-route: true # auto set global route
|
||||||
```
|
```
|
||||||
It's recommended to use fake-ip mode for the DNS server.
|
|
||||||
|
|
||||||
Clash needs elevated permission to create TUN device:
|
|
||||||
```sh
|
|
||||||
$ sudo ./clash
|
|
||||||
```
|
|
||||||
Then manually create the default route and DNS server. If your device already has some TUN device, Clash TUN might not work. In this case, fake-ip-filter may helpful.
|
|
||||||
|
|
||||||
Enjoy! :)
|
|
||||||
|
|
||||||
#### For Windows:
|
|
||||||
```yaml
|
|
||||||
tun:
|
|
||||||
enable: true
|
|
||||||
stack: gvisor # or system
|
|
||||||
dns-hijack:
|
|
||||||
- 198.18.0.2:53 # when `fake-ip-range` is 198.18.0.1/16, should hijack 198.18.0.2:53
|
|
||||||
auto-route: true # auto set global route for Windows
|
|
||||||
# It is recommended to use `interface-name`
|
|
||||||
auto-detect-interface: true # auto detect interface, conflict with `interface-name`
|
|
||||||
```
|
|
||||||
Finally, open the Clash
|
|
||||||
|
|
||||||
### Rules configuration
|
### Rules configuration
|
||||||
- Support rule `GEOSITE`.
|
- Support rule `GEOSITE`.
|
||||||
- Support rule `USER-AGENT`.
|
- Support rule-providers `RULE-SET`.
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
- Support `network` condition for all rules.
|
- Support `network` condition for all rules.
|
||||||
- Support `process` condition for all rules.
|
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
|
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
||||||
The `GEOIP` databases via [https://github.com/Loyalsoldier/geoip](https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb).
|
|
||||||
|
|
||||||
The `GEOSITE` databases via [https://github.com/Loyalsoldier/v2ray-rules-dat](https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat).
|
|
||||||
```yaml
|
```yaml
|
||||||
rules:
|
rules:
|
||||||
# network condition for all rules
|
|
||||||
- DOMAIN-SUFFIX,example.com,DIRECT,tcp
|
|
||||||
- DOMAIN-SUFFIX,example.com,REJECT,udp
|
|
||||||
|
|
||||||
# process condition for all rules (add 'P:' prefix)
|
|
||||||
- DOMAIN-SUFFIX,example.com,REJECT,P:Google Chrome Helper
|
|
||||||
|
|
||||||
|
# network(tcp/udp) condition for all rules
|
||||||
|
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||||
|
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
# USER-AGENT payload cannot include the comma character, '*' meaning any character.
|
|
||||||
- USER-AGENT,*example*,PROXY
|
|
||||||
|
|
||||||
# rule GEOSITE
|
# rule GEOSITE
|
||||||
- GEOSITE,category-ads-all,REJECT
|
- GEOSITE,category-ads-all,REJECT
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
@ -198,113 +122,94 @@ rules:
|
|||||||
- GEOSITE,youtube,PROXY
|
- GEOSITE,youtube,PROXY
|
||||||
- GEOSITE,geolocation-cn,DIRECT
|
- GEOSITE,geolocation-cn,DIRECT
|
||||||
- GEOSITE,geolocation-!cn,PROXY
|
- GEOSITE,geolocation-!cn,PROXY
|
||||||
|
|
||||||
# source IPCIDR condition for all rules in gateway proxy
|
# source IPCIDR condition for all rules in gateway proxy
|
||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
|
||||||
- GEOIP,lan,DIRECT,no-resolve
|
|
||||||
- GEOIP,cn,DIRECT
|
|
||||||
|
|
||||||
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
|
- GEOIP,private,DIRECT,no-resolve
|
||||||
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
- MATCH,PROXY
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Proxies configuration
|
### Proxies configuration
|
||||||
Support outbound protocol `VLESS`.
|
|
||||||
|
|
||||||
Support `Trojan` with XTLS.
|
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
||||||
|
|
||||||
Support relay `UDP` traffic.
|
Support `Policy Group Filter`
|
||||||
|
|
||||||
Support filtering proxy providers in proxy groups.
|
|
||||||
|
|
||||||
Support custom http request header, prefix name and V2Ray subscription URL in proxy providers.
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
|
||||||
# VLESS
|
|
||||||
- name: "vless-tls"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
network: tcp
|
|
||||||
servername: example.com
|
|
||||||
udp: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
- name: "vless-xtls"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
network: tcp
|
|
||||||
servername: example.com
|
|
||||||
flow: xtls-rprx-direct # or xtls-rprx-origin
|
|
||||||
# flow-show: true # print the XTLS direction log
|
|
||||||
# udp: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
# Trojan
|
|
||||||
- name: "trojan-xtls"
|
|
||||||
type: trojan
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
password: yourpsk
|
|
||||||
network: tcp
|
|
||||||
flow: xtls-rprx-direct # or xtls-rprx-origin
|
|
||||||
# flow-show: true # print the XTLS direction log
|
|
||||||
# udp: true
|
|
||||||
# sni: example.com # aka server name
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
# Relay chains the proxies. proxies shall not contain a relay.
|
|
||||||
# Support relay UDP traffic.
|
|
||||||
# Traffic: clash <-> ss1 <-> trojan <-> vmess <-> ss2 <-> Internet
|
|
||||||
- name: "relay-udp-over-tcp"
|
|
||||||
type: relay
|
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- trojan
|
|
||||||
- vmess
|
|
||||||
- ss2
|
|
||||||
|
|
||||||
- name: "relay-raw-udp"
|
- name: 🚀 HK Group
|
||||||
type: relay
|
type: select
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- ss2
|
|
||||||
- ss3
|
|
||||||
|
|
||||||
- name: "filtering-proxy-providers"
|
|
||||||
type: url-test
|
|
||||||
url: "http://www.gstatic.com/generate_204"
|
|
||||||
interval: 300
|
|
||||||
tolerance: 200
|
|
||||||
# lazy: true
|
|
||||||
filter: "XXX" # a regular expression
|
|
||||||
use:
|
use:
|
||||||
- provider1
|
- ALL
|
||||||
|
filter: 'HK'
|
||||||
|
|
||||||
|
- name: 🚀 US Group
|
||||||
|
type: select
|
||||||
|
use:
|
||||||
|
- ALL
|
||||||
|
filter: 'US'
|
||||||
|
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
provider1:
|
ALL:
|
||||||
type: http
|
type: http
|
||||||
url: "url" # support V2Ray subscription URL
|
url: "xxxxx"
|
||||||
interval: 3600
|
interval: 3600
|
||||||
path: ./providers/provider1.yaml
|
path: "xxxxx"
|
||||||
# filter: "xxx"
|
|
||||||
# prefix-name: "XXX-"
|
|
||||||
header: # custom http request header
|
|
||||||
User-Agent:
|
|
||||||
- "Clash/v1.10.6"
|
|
||||||
# Accept:
|
|
||||||
# - 'application/vnd.github.v3.raw'
|
|
||||||
# Authorization:
|
|
||||||
# - ' token xxxxxxxxxxx'
|
|
||||||
health-check:
|
health-check:
|
||||||
enable: false
|
enable: true
|
||||||
interval: 1200
|
interval: 600
|
||||||
# lazy: false # default value is true
|
|
||||||
url: http://www.gstatic.com/generate_204
|
url: http://www.gstatic.com/generate_204
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Support outbound transport protocol `VLESS`.
|
||||||
|
|
||||||
|
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "vless"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
servername: example.com # AKA SNI
|
||||||
|
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
- name: "vless-ws"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
tls: true
|
||||||
|
udp: true
|
||||||
|
network: ws
|
||||||
|
servername: example.com # priority over wss host
|
||||||
|
# skip-cert-verify: true
|
||||||
|
ws-opts:
|
||||||
|
path: /path
|
||||||
|
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
||||||
|
|
||||||
|
- name: "vless-grpc"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
tls: true
|
||||||
|
udp: true
|
||||||
|
network: grpc
|
||||||
|
servername: example.com # priority over wss host
|
||||||
|
# skip-cert-verify: true
|
||||||
|
grpc-opts:
|
||||||
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
@ -318,61 +223,73 @@ iptables:
|
|||||||
enable: true # default is false
|
enable: true # default is false
|
||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
Run Clash as a daemon.
|
|
||||||
|
|
||||||
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
|
||||||
```sh
|
### General installation guide for Linux
|
||||||
|
+ Create user given name `clash-meta`
|
||||||
|
|
||||||
|
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||||
|
|
||||||
|
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||||
|
|
||||||
|
+ Create folder `/etc/Clash-Meta/` as working directory
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||||
|
|
||||||
|
Create the systemd configuration file at `/etc/systemd/system/Clash-Meta.service`:
|
||||||
|
|
||||||
|
```
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Clash daemon, A rule-based proxy in Go.
|
Description=Clash-Meta Daemon, Another Clash Kernel.
|
||||||
After=network.target
|
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
|
User=clash-meta
|
||||||
|
Group=clash-meta
|
||||||
|
LimitNPROC=500
|
||||||
|
LimitNOFILE=1000000
|
||||||
CapabilityBoundingSet=cap_net_admin
|
CapabilityBoundingSet=cap_net_admin
|
||||||
|
AmbientCapabilities=cap_net_admin
|
||||||
Restart=always
|
Restart=always
|
||||||
ExecStart=/usr/local/bin/clash -d /etc/clash
|
ExecStartPre=/usr/bin/sleep 1s
|
||||||
|
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
Launch clashd on system startup with:
|
Launch clashd on system startup with:
|
||||||
```sh
|
```shell
|
||||||
$ systemctl enable clash
|
$ systemctl enable Clash-Meta
|
||||||
```
|
```
|
||||||
Launch clashd immediately with:
|
Launch clashd immediately with:
|
||||||
```sh
|
|
||||||
$ systemctl start clash
|
```shell
|
||||||
|
$ systemctl start Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
### Display Process name
|
### Display Process name
|
||||||
To display process name online by click [http://yacd.clash-plus.cf](http://yacd.clash-plus.cf) for local API by Safari or [https://yacd.clash-plus.cf](https://yacd.clash-plus.cf) for local API by Chrome.
|
|
||||||
|
|
||||||
You can download the [Dashboard](https://github.com/yaling888/yacd/archive/gh-pages.zip) into Clash home directory:
|
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||||
```sh
|
|
||||||
$ cd ~/.config/clash
|
|
||||||
$ curl -LJ https://github.com/yaling888/yacd/archive/gh-pages.zip -o yacd-gh-pages.zip
|
|
||||||
$ unzip yacd-gh-pages.zip
|
|
||||||
$ mv yacd-gh-pages dashboard
|
|
||||||
```
|
|
||||||
|
|
||||||
Add to config file:
|
To display process name in GUI please use [Dashboard For Meta](https://github.com/Clash-Mini/Dashboard).
|
||||||
```yaml
|
|
||||||
external-controller: 127.0.0.1:9090
|
|
||||||
external-ui: dashboard
|
|
||||||
```
|
|
||||||
Open [http://127.0.0.1:9090/ui/](http://127.0.0.1:9090/ui/) by web browser.
|
|
||||||
|
|
||||||
## Plus Pro Release
|

|
||||||
[Release](https://github.com/yaling888/clash/releases/tag/plus)
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
If you want to build an application that uses clash as a library, check out the the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
|
||||||
|
If you want to build an application that uses clash as a library, check out the
|
||||||
|
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
|
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
@ -17,6 +18,8 @@ import (
|
|||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
@ -38,7 +41,11 @@ func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
|||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
||||||
p.alive.Store(err == nil)
|
wasCancel := false
|
||||||
|
if err != nil {
|
||||||
|
wasCancel = strings.Contains(err.Error(), "operation was canceled")
|
||||||
|
}
|
||||||
|
p.alive.Store(err == nil || wasCancel)
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -111,6 +118,8 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
|
|
||||||
addr, err := urlToMetadata(url)
|
addr, err := urlToMetadata(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@ -149,11 +158,18 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
defer client.CloseIdleConnections()
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if unifiedDelay {
|
||||||
|
start = time.Now()
|
||||||
|
resp, err = client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
_ = resp.Body.Close()
|
_ = resp.Body.Close()
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
|
@ -1,22 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/context"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewMitm receive mitm request and return MitmContext
|
|
||||||
func NewMitm(target socks5.Addr, source net.Addr, userAgent string, conn net.Conn) *context.ConnContext {
|
|
||||||
metadata := parseSocksAddr(target)
|
|
||||||
metadata.NetWork = C.TCP
|
|
||||||
metadata.Type = C.MITM
|
|
||||||
metadata.UserAgent = userAgent
|
|
||||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
return context.NewConnContext(conn, metadata)
|
|
||||||
}
|
|
@ -2,6 +2,7 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -13,9 +14,37 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
|||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
remoteAddr := conn.RemoteAddr()
|
||||||
metadata.SrcIP = ip
|
// Filter when net.Addr interface is nil
|
||||||
metadata.SrcPort = port
|
if remoteAddr != nil {
|
||||||
|
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
||||||
|
metadata := &C.Metadata{}
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = C.INNER
|
||||||
|
metadata.DNSMode = C.DNSMapping
|
||||||
|
metadata.Host = host
|
||||||
|
metadata.AddrType = C.AtypDomainName
|
||||||
|
metadata.Process = C.ClashName
|
||||||
|
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||||
|
metadata.DstPort = port
|
||||||
|
if host == "" {
|
||||||
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
|
metadata.DstIP = ip
|
||||||
|
metadata.AddrType = C.AtypIPv4
|
||||||
|
if ip.Is6() {
|
||||||
|
metadata.AddrType = C.AtypIPv6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
|
@ -2,10 +2,12 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
|
"regexp"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -31,20 +33,25 @@ func (b *Base) Type() C.AdapterType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (b *Base) StreamConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
return c, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (b *Base) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
return c, errors.New("no support")
|
return c, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(_ context.Context, _ *C.Metadata, _ ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (b *Base) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (b *Base) SupportUOT() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (b *Base) SupportUDP() bool {
|
func (b *Base) SupportUDP() bool {
|
||||||
return b.udp
|
return b.udp
|
||||||
@ -63,7 +70,7 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(_ *C.Metadata) C.Proxy {
|
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -139,40 +146,31 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
return &packetConn{pc, []string{a.Name()}}
|
return &packetConn{pc, []string{a.Name()}}
|
||||||
}
|
}
|
||||||
|
|
||||||
type wrapConn struct {
|
func uuidMap(str string) string {
|
||||||
net.PacketConn
|
match, _ := regexp.MatchString(`[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$`, str)
|
||||||
}
|
if !match {
|
||||||
|
var Nil [16]byte
|
||||||
func (*wrapConn) Read([]byte) (int, error) {
|
h := sha1.New()
|
||||||
return 0, io.EOF
|
h.Write(Nil[:])
|
||||||
}
|
h.Write([]byte(str))
|
||||||
|
u := h.Sum(nil)[:16]
|
||||||
func (*wrapConn) Write([]byte) (int, error) {
|
u[6] = (u[6] & 0x0f) | (5 << 4)
|
||||||
return 0, io.EOF
|
u[8] = u[8]&(0xff>>2) | (0x02 << 6)
|
||||||
}
|
buf := make([]byte, 36)
|
||||||
|
hex.Encode(buf[0:8], u[0:4])
|
||||||
func (*wrapConn) RemoteAddr() net.Addr {
|
buf[8] = '-'
|
||||||
return nil
|
hex.Encode(buf[9:13], u[4:6])
|
||||||
}
|
buf[13] = '-'
|
||||||
|
hex.Encode(buf[14:18], u[6:8])
|
||||||
func WrapConn(packetConn net.PacketConn) net.Conn {
|
buf[18] = '-'
|
||||||
return &wrapConn{
|
hex.Encode(buf[19:23], u[8:10])
|
||||||
PacketConn: packetConn,
|
buf[23] = '-'
|
||||||
|
hex.Encode(buf[24:], u[10:])
|
||||||
|
return string(buf)
|
||||||
}
|
}
|
||||||
}
|
return str
|
||||||
|
|
||||||
func IsPacketConn(c net.Conn) bool {
|
|
||||||
if _, ok := c.(net.PacketConn); !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if ua, ok := c.LocalAddr().(*net.UnixAddr); ok {
|
|
||||||
return ua.Net == "unixgram"
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,6 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -20,26 +19,18 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
if !metadata.DstIP.IsValid() && c.RemoteAddr() != nil {
|
|
||||||
if h, _, err := net.SplitHostPort(c.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.DstIP = netip.MustParseAddr(h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(c, d), nil
|
return NewConn(c, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, _ *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
opts = append(opts, dialer.WithDirect())
|
opts = append(opts, dialer.WithDirect())
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewPacketConn(&directPacketConn{pc}, d), nil
|
return newPacketConn(&directPacketConn{pc}, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type directPacketConn struct {
|
type directPacketConn struct {
|
||||||
@ -55,3 +46,23 @@ func NewDirect() *Direct {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewCompatible() *Direct {
|
||||||
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: "COMPATIBLE",
|
||||||
|
tp: C.Compatible,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPass() *Direct {
|
||||||
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: "PASS",
|
||||||
|
tp: C.Pass,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -22,18 +22,20 @@ type Http struct {
|
|||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
|
option *HttpOption
|
||||||
}
|
}
|
||||||
|
|
||||||
type HttpOption struct {
|
type HttpOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UserName string `proxy:"username,omitempty"`
|
UserName string `proxy:"username,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
@ -84,15 +86,18 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//增加headers
|
||||||
|
if len(h.option.Headers) != 0 {
|
||||||
|
for key, value := range h.option.Headers {
|
||||||
|
req.Header.Add(key, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
auth := h.user + ":" + h.pass
|
auth := h.user + ":" + h.pass
|
||||||
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata.Type == C.MITM {
|
|
||||||
req.Header.Set("Origin-Request-Source-Address", metadata.SourceAddress())
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := req.Write(rw); err != nil {
|
if err := req.Write(rw); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -145,5 +150,6 @@ func NewHttp(option HttpOption) *Http {
|
|||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
|
option: &option,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,49 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Mitm struct {
|
|
||||||
*Base
|
|
||||||
serverAddr *net.TCPAddr
|
|
||||||
httpProxyClient *Http
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (m *Mitm) DialContext(_ context.Context, metadata *C.Metadata, _ ...dialer.Option) (C.Conn, error) {
|
|
||||||
c, err := net.DialTCP("tcp", nil, m.serverAddr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = c.SetKeepAlive(true)
|
|
||||||
_ = c.SetKeepAlivePeriod(60 * time.Second)
|
|
||||||
|
|
||||||
metadata.Type = C.MITM
|
|
||||||
|
|
||||||
hc, err := m.httpProxyClient.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
_ = c.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(hc, m), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMitm(serverAddr string) *Mitm {
|
|
||||||
tcpAddr, _ := net.ResolveTCPAddr("tcp", serverAddr)
|
|
||||||
return &Mitm{
|
|
||||||
Base: &Base{
|
|
||||||
name: "Mitm",
|
|
||||||
tp: C.Mitm,
|
|
||||||
},
|
|
||||||
serverAddr: tcpAddr,
|
|
||||||
httpProxyClient: NewHttp(HttpOption{}),
|
|
||||||
}
|
|
||||||
}
|
|
@ -6,49 +6,22 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
rejectCountLimit = 50
|
|
||||||
rejectDelay = time.Second * 35
|
|
||||||
)
|
|
||||||
|
|
||||||
var rejectCounter = cache.NewLRUCache[string, int](cache.WithAge[string, int](15), cache.WithStale[string, int](false), cache.WithSize[string, int](512))
|
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
*Base
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
key := metadata.RemoteAddress()
|
|
||||||
|
|
||||||
count, existed := rejectCounter.Get(key)
|
|
||||||
if !existed {
|
|
||||||
count = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
count = count + 1
|
|
||||||
|
|
||||||
rejectCounter.Set(key, count)
|
|
||||||
|
|
||||||
if count > rejectCountLimit {
|
|
||||||
c, _ := net.Pipe()
|
|
||||||
|
|
||||||
_ = c.SetDeadline(time.Now().Add(rejectDelay))
|
|
||||||
|
|
||||||
return NewConn(c, r), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(&nopConn{}, r), nil
|
return NewConn(&nopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return NewPacketConn(&nopPacketConn{}, r), nil
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
|
@ -10,10 +10,11 @@ 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 {
|
||||||
@ -73,21 +74,6 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
if !IsPacketConn(c) {
|
|
||||||
return c, fmt.Errorf("%s connect error: can not convert net.Conn to net.PacketConn", ss.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ss.addr)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc := ss.cipher.PacketConn(c.(net.PacketConn))
|
|
||||||
return WrapConn(&ssPacketConn{PacketConn: pc, rAddr: addr}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
@ -109,13 +95,14 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := ss.StreamPacketConn(WrapConn(pc), metadata)
|
addr, err := resolveUDPAddr("udp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = pc.Close()
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), ss), nil
|
pc = ss.cipher.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
|
@ -8,11 +8,12 @@ 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 {
|
||||||
@ -58,22 +59,6 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
if !IsPacketConn(c) {
|
|
||||||
return c, fmt.Errorf("%s connect error: can not convert net.Conn to net.PacketConn", ssr.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ssr.addr)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc := ssr.cipher.PacketConn(c.(net.PacketConn))
|
|
||||||
pc = ssr.protocol.PacketConn(pc)
|
|
||||||
return WrapConn(&ssPacketConn{PacketConn: pc, rAddr: addr}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
||||||
@ -95,13 +80,15 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := ssr.StreamPacketConn(WrapConn(pc), metadata)
|
addr, err := resolveUDPAddr("udp", ssr.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = pc.Close()
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), ssr), nil
|
pc = ssr.cipher.PacketConn(pc)
|
||||||
|
pc = ssr.protocol.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
|
@ -53,23 +53,15 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
err := snell.WriteUDPHeader(c, s.version)
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (s *Snell) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
|
||||||
|
|
||||||
err := snell.WriteUDPHeader(c, s.version)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return WrapConn(snell.PacketConn(c)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
if s.version == snell.Version2 && len(opts) == 0 {
|
if s.version == snell.Version2 && len(opts) == 0 {
|
||||||
@ -80,7 +72,7 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
||||||
_ = c.Close()
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
@ -105,14 +97,20 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
pc, err := s.StreamPacketConn(c, metadata)
|
return s.ListenPacketOnStreamConn(c, metadata)
|
||||||
if err != nil {
|
}
|
||||||
_ = c.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewPacketConn(pc.(net.PacketConn), s), nil
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (s *Snell) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
|
@ -37,59 +37,12 @@ type Socks5Option struct {
|
|||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
|
||||||
c, _, err = ss.streamConn(c, metadata)
|
|
||||||
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) StreamSocks5PacketConn(c net.Conn, pc net.PacketConn, metadata *C.Metadata) (net.PacketConn, error) {
|
|
||||||
if c == nil {
|
|
||||||
return pc, fmt.Errorf("%s connect error: parameter net.Conn is nil", ss.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
if pc == nil {
|
|
||||||
return pc, fmt.Errorf("%s connect error: parameter net.PacketConn is nil", ss.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
cc, bindAddr, err := ss.streamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c = cc
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
_, _ = io.Copy(io.Discard, c)
|
|
||||||
_ = c.Close()
|
|
||||||
// A UDP association terminates when the TCP connection that the UDP
|
|
||||||
// ASSOCIATE request arrived on terminates. RFC1928
|
|
||||||
_ = pc.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Support unspecified UDP bind address.
|
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
return pc, errors.New("invalid UDP bind address")
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
return &socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) streamConn(c net.Conn, metadata *C.Metadata) (_ net.Conn, bindAddr socks5.Addr, err error) {
|
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err := cc.Handshake()
|
err := cc.Handshake()
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c, nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,14 +53,10 @@ func (ss *Socks5) streamConn(c net.Conn, metadata *C.Metadata) (_ net.Conn, bind
|
|||||||
Password: ss.pass,
|
Password: ss.pass,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
if metadata.NetWork == C.UDP {
|
return nil, err
|
||||||
bindAddr, err = socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
|
||||||
} else {
|
|
||||||
bindAddr, err = socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user)
|
|
||||||
}
|
}
|
||||||
|
return c, nil
|
||||||
return c, bindAddr, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -132,24 +81,61 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ss.tls {
|
||||||
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
|
err = cc.Handshake()
|
||||||
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
var user *socks5.User
|
||||||
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("client hanshake error: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
go func() {
|
||||||
|
io.Copy(io.Discard, c)
|
||||||
|
c.Close()
|
||||||
|
// A UDP association terminates when the TCP connection that the UDP
|
||||||
|
// ASSOCIATE request arrived on terminates. RFC1928
|
||||||
|
pc.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
pc, err = ss.StreamSocks5PacketConn(c, pc, metadata)
|
// Support unspecified UDP bind address.
|
||||||
if err != nil {
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
return
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(pc, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
@ -213,6 +199,6 @@ func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (uc *socksPacketConn) Close() error {
|
func (uc *socksPacketConn) Close() error {
|
||||||
_ = uc.tcpConn.Close()
|
uc.tcpConn.Close()
|
||||||
return uc.PacketConn.Close()
|
return uc.PacketConn.Close()
|
||||||
}
|
}
|
||||||
|
@ -72,7 +72,8 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
return t.instance.StreamConn(c)
|
return t.instance.StreamConn(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) trojanStream(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
if t.transport != nil {
|
if t.transport != nil {
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
@ -84,63 +85,43 @@ func (t *Trojan) trojanStream(c net.Conn, metadata *C.Metadata) (net.Conn, error
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = t.instance.PrepareXTLSConn(c)
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
return t.trojanStream(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
var err error
|
|
||||||
c, err = t.trojanStream(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
|
||||||
return WrapConn(pc), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
var c net.Conn
|
|
||||||
|
|
||||||
// gun transport
|
// gun transport
|
||||||
if t.transport != nil && len(opts) == 0 {
|
if t.transport != nil && len(opts) == 0 {
|
||||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
|
|
||||||
c, err = t.instance.PrepareXTLSConn(c)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, t), nil
|
return NewConn(c, t), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
@ -160,44 +141,38 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
|
|
||||||
// gun transport
|
// grpc transport
|
||||||
if t.transport != nil && len(opts) == 0 {
|
if t.transport != nil && len(opts) == 0 {
|
||||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
} else {
|
||||||
c, err = t.instance.PrepareXTLSConn(c)
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata)); err != nil {
|
tcpKeepAlive(c)
|
||||||
return nil, err
|
c, err = t.plainStream(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
|
||||||
|
|
||||||
return NewPacketConn(pc, t), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
return t.ListenPacketOnStreamConn(c, metadata)
|
||||||
if err != nil {
|
}
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) SupportUOT() bool {
|
||||||
c, err = t.StreamPacketConn(c, metadata)
|
return true
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), t), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
|
@ -2,8 +2,11 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
@ -11,6 +14,12 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalClientSessionCache tls.ClientSessionCache
|
||||||
|
globalClientXSessionCache xtls.ClientSessionCache
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
_ = tcp.SetKeepAlive(true)
|
_ = tcp.SetKeepAlive(true)
|
||||||
@ -18,6 +27,20 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getClientSessionCache() tls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return globalClientSessionCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func getClientXSessionCache() xtls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
globalClientXSessionCache = xtls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return globalClientXSessionCache
|
||||||
|
}
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
aType := uint8(metadata.AddrType)
|
aType := uint8(metadata.AddrType)
|
||||||
@ -52,7 +75,7 @@ func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil && c != nil {
|
if err != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -46,6 +46,7 @@ type VlessOption struct {
|
|||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
@ -58,17 +59,10 @@ type VlessOption struct {
|
|||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
if v.option.WSOpts.Path == "" {
|
|
||||||
v.option.WSOpts.Path = v.option.WSPath
|
|
||||||
}
|
|
||||||
if len(v.option.WSOpts.Headers) == 0 {
|
|
||||||
v.option.WSOpts.Headers = v.option.WSHeaders
|
|
||||||
}
|
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
@ -99,7 +93,6 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
@ -148,26 +141,6 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (v *Vless) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return WrapConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
@ -187,7 +160,7 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||||
|
|
||||||
} else {
|
} else if v.option.TLS {
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
@ -203,6 +176,8 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) isXTLSEnabled() bool {
|
func (v *Vless) isXTLSEnabled() bool {
|
||||||
@ -240,18 +215,18 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -259,27 +234,32 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
return NewPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamPacketConn(c, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), v), nil
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (v *Vless) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
@ -287,18 +267,18 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType {
|
||||||
case C.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
addrType = byte(vless.AtypIPv4)
|
addrType = vless.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypIPv6:
|
case C.AtypIPv6:
|
||||||
addrType = byte(vless.AtypIPv6)
|
addrType = vless.AtypIPv6
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypDomainName:
|
case C.AtypDomainName:
|
||||||
addrType = byte(vless.AtypDomainName)
|
addrType = vless.AtypDomainName
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
copy(addr[1:], metadata.Host)
|
||||||
}
|
}
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
@ -313,29 +293,40 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
type vlessPacketConn struct {
|
type vlessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
cache [2]byte
|
|
||||||
remain int
|
remain int
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
|
cache [2]byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func (vc *vlessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
func (c *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
||||||
|
binary.BigEndian.PutUint16(c.cache[:], uint16(len(payload)))
|
||||||
|
|
||||||
|
if _, err := c.Conn.Write(c.cache[:]); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Conn.Write(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
total := len(b)
|
total := len(b)
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if total < maxLength {
|
if total <= maxLength {
|
||||||
return vc.writePacket(b)
|
return c.writePacket(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
offset := 0
|
offset := 0
|
||||||
for {
|
|
||||||
|
for offset < total {
|
||||||
cursor := offset + maxLength
|
cursor := offset + maxLength
|
||||||
if cursor > total {
|
if cursor > total {
|
||||||
cursor = total
|
cursor = total
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := vc.writePacket(b[offset:cursor])
|
n, err := c.writePacket(b[offset:cursor])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return offset + n, err
|
return offset + n, err
|
||||||
}
|
}
|
||||||
@ -349,33 +340,32 @@ func (vc *vlessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
|||||||
return total, nil
|
return total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
vc.mux.Lock()
|
c.mux.Lock()
|
||||||
defer vc.mux.Unlock()
|
defer c.mux.Unlock()
|
||||||
|
|
||||||
if vc.remain != 0 {
|
if c.remain > 0 {
|
||||||
length := len(b)
|
length := len(b)
|
||||||
if length > vc.remain {
|
if c.remain < length {
|
||||||
length = vc.remain
|
length = c.remain
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := vc.Conn.Read(b[:length])
|
n, err := c.Conn.Read(b[:length])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, vc.rAddr, err
|
return 0, c.rAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
vc.remain -= n
|
c.remain -= n
|
||||||
|
return n, c.rAddr, nil
|
||||||
return n, vc.rAddr, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := vc.Conn.Read(b[:2]); err != nil {
|
if _, err := c.Conn.Read(b[:2]); err != nil {
|
||||||
return 0, vc.rAddr, err
|
return 0, c.rAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
total := int(binary.BigEndian.Uint16(b[:2]))
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, vc.rAddr, nil
|
return 0, c.rAddr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
length := len(b)
|
length := len(b)
|
||||||
@ -383,23 +373,13 @@ func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
length = total
|
length = total
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := io.ReadFull(vc.Conn, b[:length]); err != nil {
|
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
||||||
return 0, vc.rAddr, errors.New("read packet error")
|
return 0, c.rAddr, errors.New("read packet error")
|
||||||
}
|
}
|
||||||
|
|
||||||
vc.remain = total - length
|
c.remain = total - length
|
||||||
|
|
||||||
return length, vc.rAddr, nil
|
return length, c.rAddr, nil
|
||||||
}
|
|
||||||
|
|
||||||
func (vc *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
|
||||||
binary.BigEndian.PutUint16(vc.cache[:], uint16(len(payload)))
|
|
||||||
|
|
||||||
if _, err := vc.Conn.Write(vc.cache[:]); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return vc.Conn.Write(payload)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
func NewVless(option VlessOption) (*Vless, error) {
|
||||||
@ -416,7 +396,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
client, err := vless.NewClient(uuidMap(option.UUID), addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -194,26 +195,6 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (v *Vmess) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return c, fmt.Errorf("can't resolve ip: %w", err)
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return c, fmt.Errorf("new vmess client error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return WrapConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
// gun transport
|
// gun transport
|
||||||
@ -245,18 +226,18 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -264,33 +245,38 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
return NewPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamPacketConn(c, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), v), nil
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
security := strings.ToLower(option.Cipher)
|
security := strings.ToLower(option.Cipher)
|
||||||
client, err := vmess.NewClient(vmess.Config{
|
client, err := vmess.NewClient(vmess.Config{
|
||||||
UUID: option.UUID,
|
UUID: uuidMap(option.UUID),
|
||||||
AlterID: uint16(option.AlterID),
|
AlterID: uint16(option.AlterID),
|
||||||
Security: security,
|
Security: security,
|
||||||
HostName: option.Server,
|
HostName: option.Server,
|
||||||
@ -392,7 +378,7 @@ type vmessPacketConn struct {
|
|||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,24 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultGetProxiesDuration = time.Second * 5
|
|
||||||
)
|
|
||||||
|
|
||||||
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
|
||||||
proxies := []C.Proxy{}
|
|
||||||
for _, provider := range providers {
|
|
||||||
if touch {
|
|
||||||
proxies = append(proxies, provider.ProxiesWithTouch()...)
|
|
||||||
} else {
|
|
||||||
proxies = append(proxies, provider.Proxies()...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
|
@ -3,19 +3,21 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single[[]C.Proxy]
|
failedTimes *atomic.Int32
|
||||||
providers []provider.ProxyProvider
|
failedTime *atomic.Int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@ -29,7 +31,12 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
|
f.failedTimes.Store(-1)
|
||||||
|
f.failedTime.Store(-1)
|
||||||
|
} else {
|
||||||
|
f.onDialFailed()
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,10 +46,41 @@ func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
|||||||
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(f)
|
pc.AppendToChains(f)
|
||||||
|
f.failedTimes.Store(-1)
|
||||||
|
f.failedTime.Store(-1)
|
||||||
|
} else {
|
||||||
|
f.onDialFailed()
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) onDialFailed() {
|
||||||
|
if f.failedTime.Load() == -1 {
|
||||||
|
log.Warnln("%s first failed", f.Name())
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
f.failedTime.Store(now)
|
||||||
|
f.failedTimes.Store(1)
|
||||||
|
} else {
|
||||||
|
if f.failedTime.Load()-time.Now().UnixMilli() > 5*time.Second.Milliseconds() {
|
||||||
|
f.failedTimes.Store(-1)
|
||||||
|
f.failedTime.Store(-1)
|
||||||
|
} else {
|
||||||
|
failedCount := f.failedTimes.Inc()
|
||||||
|
log.Warnln("%s failed count: %d", f.Name(), failedCount)
|
||||||
|
if failedCount >= 5 {
|
||||||
|
log.Warnln("because %s failed multiple times, active health check", f.Name())
|
||||||
|
for _, proxyProvider := range f.providers {
|
||||||
|
go proxyProvider.HealthCheck()
|
||||||
|
}
|
||||||
|
|
||||||
|
f.failedTimes.Store(-1)
|
||||||
|
f.failedTime.Store(-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (f *Fallback) SupportUDP() bool {
|
func (f *Fallback) SupportUDP() bool {
|
||||||
if f.disableUDP {
|
if f.disableUDP {
|
||||||
@ -55,8 +93,8 @@ func (f *Fallback) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range f.proxies(false) {
|
for _, proxy := range f.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -72,16 +110,8 @@ func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
|
||||||
elm, _, _ := f.single.Do(func() ([]C.Proxy, error) {
|
|
||||||
return getProvidersProxies(f.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||||
proxies := f.proxies(touch)
|
proxies := f.GetProxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
return proxy
|
return proxy
|
||||||
@ -93,14 +123,18 @@ func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
|||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.Fallback,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.Fallback,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
disableUDP: option.DisableUDP,
|
||||||
providers: providers,
|
failedTimes: atomic.NewInt32(-1),
|
||||||
disableUDP: option.DisableUDP,
|
failedTime: atomic.NewInt64(-1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
98
adapter/outboundgroup/groupbase.go
Normal file
98
adapter/outboundgroup/groupbase.go
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GroupBase struct {
|
||||||
|
*outbound.Base
|
||||||
|
filter *regexp2.Regexp
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
versions sync.Map // map[string]uint
|
||||||
|
proxies sync.Map // map[string][]C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
type GroupBaseOption struct {
|
||||||
|
outbound.BaseOption
|
||||||
|
filter string
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
|
var filter *regexp2.Regexp = nil
|
||||||
|
if opt.filter != "" {
|
||||||
|
filter = regexp2.MustCompile(opt.filter, 0)
|
||||||
|
}
|
||||||
|
return &GroupBase{
|
||||||
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
|
filter: filter,
|
||||||
|
providers: opt.providers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||||
|
if gb.filter == nil {
|
||||||
|
var proxies []C.Proxy
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
if touch {
|
||||||
|
proxies = append(proxies, pd.ProxiesWithTouch()...)
|
||||||
|
} else {
|
||||||
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
||||||
|
//TODO("Touch Version 没变的")
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
if pd.VehicleType() == types.Compatible {
|
||||||
|
if touch {
|
||||||
|
gb.proxies.Store(pd.Name(), pd.ProxiesWithTouch())
|
||||||
|
} else {
|
||||||
|
gb.proxies.Store(pd.Name(), pd.Proxies())
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.versions.Store(pd.Name(), pd.Version())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if version, ok := gb.versions.Load(pd.Name()); !ok || version != pd.Version() {
|
||||||
|
var (
|
||||||
|
proxies []C.Proxy
|
||||||
|
newProxies []C.Proxy
|
||||||
|
)
|
||||||
|
|
||||||
|
if touch {
|
||||||
|
proxies = pd.ProxiesWithTouch()
|
||||||
|
} else {
|
||||||
|
proxies = pd.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range proxies {
|
||||||
|
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.proxies.Store(pd.Name(), newProxies)
|
||||||
|
gb.versions.Store(pd.Name(), pd.Version())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var proxies []C.Proxy
|
||||||
|
gb.proxies.Range(func(key, value any) bool {
|
||||||
|
proxies = append(proxies, value.([]C.Proxy)...)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
@ -9,7 +9,6 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -20,10 +19,8 @@ import (
|
|||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single[[]C.Proxy]
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -135,22 +132,14 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
proxies := lb.proxies(true)
|
proxies := lb.GetProxies(true)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
|
||||||
elm, _, _ := lb.single.Do(func() ([]C.Proxy, error) {
|
|
||||||
return getProvidersProxies(lb.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range lb.proxies(false) {
|
for _, proxy := range lb.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -170,14 +159,16 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
}
|
}
|
||||||
return &LoadBalance{
|
return &LoadBalance{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.LoadBalance,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.LoadBalance,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}, nil
|
}, nil
|
||||||
|
@ -3,7 +3,6 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
@ -39,23 +38,10 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
Lazy: true,
|
Lazy: true,
|
||||||
}
|
}
|
||||||
|
if err := decoder.Decode(config, groupOption); err != nil {
|
||||||
var (
|
|
||||||
filterRegx *regexp.Regexp
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
|
|
||||||
if err = decoder.Decode(config, groupOption); err != nil {
|
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
if groupOption.Filter != "" {
|
|
||||||
filterRegx, err = regexp.Compile(groupOption.Filter)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.Type == "" || groupOption.Name == "" {
|
if groupOption.Type == "" || groupOption.Name == "" {
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
@ -105,11 +91,13 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(groupOption.Use) != 0 {
|
if len(groupOption.Use) != 0 {
|
||||||
list, err := getProviders(providersMap, groupOption, filterRegx)
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
providers = append(providers, list...)
|
providers = append(providers, list...)
|
||||||
|
} else {
|
||||||
|
groupOption.Filter = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
@ -145,13 +133,8 @@ func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProviders(mapping map[string]types.ProxyProvider, groupOption *GroupCommonOption, filterRegx *regexp.Regexp) ([]types.ProxyProvider, error) {
|
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
||||||
var (
|
var ps []types.ProxyProvider
|
||||||
ps []types.ProxyProvider
|
|
||||||
list = groupOption.Use
|
|
||||||
groupName = groupOption.Name
|
|
||||||
)
|
|
||||||
|
|
||||||
for _, name := range list {
|
for _, name := range list {
|
||||||
p, ok := mapping[name]
|
p, ok := mapping[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -161,27 +144,6 @@ func getProviders(mapping map[string]types.ProxyProvider, groupOption *GroupComm
|
|||||||
if p.VehicleType() == types.Compatible {
|
if p.VehicleType() == types.Compatible {
|
||||||
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if filterRegx != nil {
|
|
||||||
var hc *provider.HealthCheck
|
|
||||||
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
|
||||||
hc = provider.NewHealthCheck([]C.Proxy{}, "", 0, true)
|
|
||||||
} else {
|
|
||||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
|
||||||
return nil, errMissHealthCheck
|
|
||||||
}
|
|
||||||
hc = provider.NewHealthCheck([]C.Proxy{}, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok = mapping[groupName]; ok {
|
|
||||||
groupName += "->" + p.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
pd := p.(*provider.ProxySetProvider)
|
|
||||||
p = provider.NewProxyFilterProvider(groupName, pd, hc, filterRegx)
|
|
||||||
pd.RegisterProvidersInUse(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
ps = append(ps, p)
|
ps = append(ps, p)
|
||||||
}
|
}
|
||||||
return ps, nil
|
return ps, nil
|
||||||
|
@ -4,32 +4,20 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
single *singledo.Single[[]C.Proxy]
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
var proxies []C.Proxy
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
for _, proxy := range r.proxies(metadata, true) {
|
|
||||||
if proxy.Type() != C.Direct {
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch len(proxies) {
|
switch len(proxies) {
|
||||||
case 0:
|
case 0:
|
||||||
@ -38,165 +26,115 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := r.streamContext(ctx, proxies, r.Base.DialOptions(opts...)...)
|
first := proxies[0]
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
c, err = last.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return outbound.NewConn(c, r), nil
|
conn := outbound.NewConn(c, last)
|
||||||
|
|
||||||
|
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||||
|
conn.AppendToChains(chainProxies[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
conn.AppendToChains(r)
|
||||||
|
|
||||||
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
var proxies []C.Proxy
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
for _, proxy := range r.proxies(metadata, true) {
|
|
||||||
if proxy.Type() != C.Direct {
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
length := len(proxies)
|
switch len(proxies) {
|
||||||
|
|
||||||
switch length {
|
|
||||||
case 0:
|
case 0:
|
||||||
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
case 1:
|
case 1:
|
||||||
proxy := proxies[0]
|
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
if !proxy.SupportUDP() {
|
|
||||||
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported", proxy.Addr(), proxy.Name())
|
|
||||||
}
|
|
||||||
return proxy.ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
first := proxies[0]
|
||||||
firstIndex = 0
|
last := proxies[len(proxies)-1]
|
||||||
nextIndex = 1
|
|
||||||
lastUDPOverTCPIndex = -1
|
|
||||||
rawUDPRelay = false
|
|
||||||
|
|
||||||
first = proxies[firstIndex]
|
|
||||||
last = proxies[length-1]
|
|
||||||
|
|
||||||
c net.Conn
|
|
||||||
cc net.Conn
|
|
||||||
err error
|
|
||||||
currentMeta *C.Metadata
|
|
||||||
)
|
|
||||||
|
|
||||||
if !last.SupportUDP() {
|
|
||||||
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported in relay chains", last.Addr(), last.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
rawUDPRelay, lastUDPOverTCPIndex = isRawUDPRelay(proxies)
|
|
||||||
|
|
||||||
if first.Type() == C.Socks5 {
|
|
||||||
cc1, err1 := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
|
||||||
if err1 != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
cc = cc1
|
|
||||||
tcpKeepAlive(cc)
|
|
||||||
|
|
||||||
var pc net.PacketConn
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", r.Base.DialOptions(opts...)...)
|
|
||||||
c = outbound.WrapConn(pc)
|
|
||||||
} else if rawUDPRelay {
|
|
||||||
var pc net.PacketConn
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", r.Base.DialOptions(opts...)...)
|
|
||||||
c = outbound.WrapConn(pc)
|
|
||||||
} else {
|
|
||||||
firstIndex = lastUDPOverTCPIndex
|
|
||||||
nextIndex = firstIndex + 1
|
|
||||||
first = proxies[firstIndex]
|
|
||||||
c, err = r.streamContext(ctx, proxies[:nextIndex], r.Base.DialOptions(opts...)...)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
if nextIndex < length {
|
var currentMeta *C.Metadata
|
||||||
for i, proxy := range proxies[nextIndex:] { // raw udp in loop
|
for _, proxy := range proxies[1:] {
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
|
||||||
currentMeta.NetWork = C.UDP
|
|
||||||
|
|
||||||
if !isRawUDP(first) && !first.SupportUDP() {
|
|
||||||
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported in relay chains", first.Addr(), first.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
if needResolveIP(first, currentMeta) {
|
|
||||||
var ip netip.Addr
|
|
||||||
ip, err = resolver.ResolveProxyServerHost(currentMeta.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
|
||||||
}
|
|
||||||
currentMeta.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
if cc != nil { // socks5
|
|
||||||
c, err = streamSocks5PacketConn(first, cc, c, currentMeta)
|
|
||||||
cc = nil
|
|
||||||
} else {
|
|
||||||
c, err = first.StreamPacketConn(c, currentMeta)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if proxy.Type() == C.Socks5 {
|
|
||||||
endIndex := nextIndex + i + 1
|
|
||||||
cc, err = r.streamContext(ctx, proxies[:endIndex], r.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
if cc != nil {
|
c, err = last.StreamConn(c, metadata)
|
||||||
c, err = streamSocks5PacketConn(last, cc, c, metadata)
|
|
||||||
} else {
|
|
||||||
c, err = last.StreamPacketConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return outbound.NewPacketConn(c.(net.PacketConn), r), nil
|
var pc C.PacketConn
|
||||||
|
pc, err = last.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||||
|
pc.AppendToChains(chainProxies[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
pc.AppendToChains(r)
|
||||||
|
|
||||||
|
return pc, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (r *Relay) SupportUDP() bool {
|
func (r *Relay) SupportUDP() bool {
|
||||||
proxies := r.rawProxies(true)
|
proxies, _ := r.proxies(nil, false)
|
||||||
|
if len(proxies) == 0 { // C.Direct
|
||||||
l := len(proxies)
|
|
||||||
|
|
||||||
if l == 0 {
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
last := proxies[l-1]
|
return last.SupportUDP() && last.SupportUOT()
|
||||||
|
|
||||||
return isRawUDP(last) || last.SupportUDP()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (r *Relay) MarshalJSON() ([]byte, error) {
|
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range r.rawProxies(false) {
|
for _, proxy := range r.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -205,114 +143,44 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy) {
|
||||||
elm, _, _ := r.single.Do(func() ([]C.Proxy, error) {
|
rawProxies := r.GetProxies(touch)
|
||||||
return getProvidersProxies(r.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
var proxies []C.Proxy
|
||||||
}
|
var chainProxies []C.Proxy
|
||||||
|
var targetProxies []C.Proxy
|
||||||
|
|
||||||
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
|
for n, proxy := range rawProxies {
|
||||||
proxies := r.rawProxies(touch)
|
proxies = append(proxies, proxy)
|
||||||
|
chainProxies = append(chainProxies, proxy)
|
||||||
for n, proxy := range proxies {
|
|
||||||
subproxy := proxy.Unwrap(metadata)
|
subproxy := proxy.Unwrap(metadata)
|
||||||
for subproxy != nil {
|
for subproxy != nil {
|
||||||
|
chainProxies = append(chainProxies, subproxy)
|
||||||
proxies[n] = subproxy
|
proxies[n] = subproxy
|
||||||
subproxy = subproxy.Unwrap(metadata)
|
subproxy = subproxy.Unwrap(metadata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies
|
for _, proxy := range proxies {
|
||||||
}
|
if proxy.Type() != C.Direct && proxy.Type() != C.Compatible {
|
||||||
|
targetProxies = append(targetProxies, proxy)
|
||||||
func (r *Relay) streamContext(ctx context.Context, proxies []C.Proxy, opts ...dialer.Option) (net.Conn, error) {
|
|
||||||
first := proxies[0]
|
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
if len(proxies) > 1 {
|
|
||||||
var currentMeta *C.Metadata
|
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, nil
|
return targetProxies, chainProxies
|
||||||
}
|
|
||||||
|
|
||||||
func streamSocks5PacketConn(proxy C.Proxy, cc, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
pc, err := proxy.(*adapter.Proxy).ProxyAdapter.(*outbound.Socks5).StreamSocks5PacketConn(cc, c.(net.PacketConn), metadata)
|
|
||||||
return outbound.WrapConn(pc), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func isRawUDPRelay(proxies []C.Proxy) (bool, int) {
|
|
||||||
var (
|
|
||||||
lastIndex = len(proxies) - 1
|
|
||||||
last = proxies[lastIndex]
|
|
||||||
isLastRawUDP = isRawUDP(last)
|
|
||||||
isUDPOverTCP = false
|
|
||||||
lastUDPOverTCPIndex = -1
|
|
||||||
)
|
|
||||||
|
|
||||||
for i := lastIndex; i >= 0; i-- {
|
|
||||||
p := proxies[i]
|
|
||||||
|
|
||||||
isUDPOverTCP = isUDPOverTCP || !isRawUDP(p)
|
|
||||||
|
|
||||||
if isLastRawUDP && isUDPOverTCP && lastUDPOverTCPIndex == -1 {
|
|
||||||
lastUDPOverTCPIndex = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isLastRawUDP {
|
|
||||||
lastUDPOverTCPIndex = lastIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
return !isUDPOverTCP, lastUDPOverTCPIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
func isRawUDP(proxy C.ProxyAdapter) bool {
|
|
||||||
if proxy.Type() == C.Shadowsocks || proxy.Type() == C.ShadowsocksR || proxy.Type() == C.Socks5 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func needResolveIP(proxy C.ProxyAdapter, metadata *C.Metadata) bool {
|
|
||||||
if metadata.Resolved() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if proxy.Type() != C.Vmess && proxy.Type() != C.Vless {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
return &Relay{
|
return &Relay{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.Relay,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.Relay,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
"",
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,18 +6,15 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single[C.Proxy]
|
|
||||||
selected string
|
selected string
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -49,8 +46,8 @@ func (s *Selector) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range getProvidersProxies(s.providers, false) {
|
for _, proxy := range s.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,10 +63,9 @@ func (s *Selector) Now() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
func (s *Selector) Set(name string) error {
|
||||||
for _, proxy := range getProvidersProxies(s.providers, false) {
|
for _, proxy := range s.GetProxies(false) {
|
||||||
if proxy.Name() == name {
|
if proxy.Name() == name {
|
||||||
s.selected = name
|
s.selected = name
|
||||||
s.single.Reset()
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -78,37 +74,34 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
||||||
return s.selectedProxy(true)
|
return s.selectedProxy(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
elm, _, _ := s.single.Do(func() (C.Proxy, error) {
|
proxies := s.GetProxies(touch)
|
||||||
proxies := getProvidersProxies(s.providers, touch)
|
for _, proxy := range proxies {
|
||||||
for _, proxy := range proxies {
|
if proxy.Name() == s.selected {
|
||||||
if proxy.Name() == s.selected {
|
return proxy
|
||||||
return proxy, nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return proxies[0], nil
|
return proxies[0]
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
||||||
selected := providers[0].Proxies()[0].Name()
|
|
||||||
return &Selector{
|
return &Selector{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.Selector,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.Selector,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[C.Proxy](defaultGetProxiesDuration),
|
selected: "COMPATIBLE",
|
||||||
providers: providers,
|
|
||||||
selected: selected,
|
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,8 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"go.uber.org/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
@ -21,13 +23,13 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
single *singledo.Single[[]C.Proxy]
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
failedTimes *atomic.Int32
|
||||||
providers []provider.ProxyProvider
|
failedTime *atomic.Int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
func (u *URLTest) Now() string {
|
||||||
@ -39,6 +41,10 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
|
u.failedTimes.Store(-1)
|
||||||
|
u.failedTime.Store(-1)
|
||||||
|
} else {
|
||||||
|
u.onDialFailed()
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -48,26 +54,22 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(u)
|
pc.AppendToChains(u)
|
||||||
|
u.failedTimes.Store(-1)
|
||||||
|
u.failedTime.Store(-1)
|
||||||
|
} else {
|
||||||
|
u.onDialFailed()
|
||||||
}
|
}
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
||||||
return u.fast(true)
|
return u.fast(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
|
||||||
elm, _, _ := u.single.Do(func() ([]C.Proxy, error) {
|
|
||||||
return getProvidersProxies(u.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.proxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
@ -110,8 +112,8 @@ func (u *URLTest) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range u.proxies(false) {
|
for _, proxy := range u.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -121,6 +123,32 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) onDialFailed() {
|
||||||
|
if u.failedTime.Load() == -1 {
|
||||||
|
log.Warnln("%s first failed", u.Name())
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
u.failedTime.Store(now)
|
||||||
|
u.failedTimes.Store(1)
|
||||||
|
} else {
|
||||||
|
if u.failedTime.Load()-time.Now().UnixMilli() > 5*1000 {
|
||||||
|
u.failedTimes.Store(-1)
|
||||||
|
u.failedTime.Store(-1)
|
||||||
|
} else {
|
||||||
|
failedCount := u.failedTimes.Inc()
|
||||||
|
log.Warnln("%s failed count: %d", u.Name(), failedCount)
|
||||||
|
if failedCount >= 5 {
|
||||||
|
log.Warnln("because %s failed multiple times, active health check", u.Name())
|
||||||
|
for _, proxyProvider := range u.providers {
|
||||||
|
go proxyProvider.HealthCheck()
|
||||||
|
}
|
||||||
|
|
||||||
|
u.failedTimes.Store(-1)
|
||||||
|
u.failedTime.Store(-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
@ -136,16 +164,20 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
|||||||
|
|
||||||
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
urlTest := &URLTest{
|
urlTest := &URLTest{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.URLTest,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.URLTest,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
disableUDP: option.DisableUDP,
|
||||||
providers: providers,
|
failedTimes: atomic.NewInt32(-1),
|
||||||
disableUDP: option.DisableUDP,
|
failedTime: atomic.NewInt64(-1),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
@ -24,7 +24,8 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return addr, nil
|
err = nil
|
||||||
|
return
|
||||||
} else if ip.Is4() {
|
} else if ip.Is4() {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
AddrType: C.AtypIPv4,
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
@ -40,9 +40,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
socksOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy = outbound.NewSocks5(*socksOption)
|
proxy = outbound.NewSocks5(*socksOption)
|
||||||
case "http":
|
case "http":
|
||||||
httpOption := &outbound.HttpOption{}
|
httpOption := &outbound.HttpOption{}
|
||||||
@ -50,9 +47,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
httpOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy = outbound.NewHttp(*httpOption)
|
proxy = outbound.NewHttp(*httpOption)
|
||||||
case "vmess":
|
case "vmess":
|
||||||
vmessOption := &outbound.VmessOption{
|
vmessOption := &outbound.VmessOption{
|
||||||
@ -65,9 +59,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
vmessOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{}
|
||||||
@ -75,9 +66,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
vlessOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewVless(*vlessOption)
|
proxy, err = outbound.NewVless(*vlessOption)
|
||||||
case "snell":
|
case "snell":
|
||||||
snellOption := &outbound.SnellOption{}
|
snellOption := &outbound.SnellOption{}
|
||||||
@ -92,9 +80,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
trojanOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
|
@ -16,28 +16,28 @@ var (
|
|||||||
dirMode os.FileMode = 0o755
|
dirMode os.FileMode = 0o755
|
||||||
)
|
)
|
||||||
|
|
||||||
type parser[V any] func([]byte) (V, error)
|
type parser = func([]byte) (any, error)
|
||||||
|
|
||||||
type fetcher[V any] struct {
|
type fetcher struct {
|
||||||
name string
|
name string
|
||||||
vehicle types.Vehicle
|
vehicle types.Vehicle
|
||||||
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[V]
|
parser parser
|
||||||
onUpdate func(V)
|
onUpdate func(any)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Name() string {
|
func (f *fetcher) Name() string {
|
||||||
return f.name
|
return f.name
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) VehicleType() types.VehicleType {
|
func (f *fetcher) VehicleType() types.VehicleType {
|
||||||
return f.vehicle.Type()
|
return f.vehicle.Type()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Initial() (V, error) {
|
func (f *fetcher) Initial() (any, error) {
|
||||||
var (
|
var (
|
||||||
buf []byte
|
buf []byte
|
||||||
err error
|
err error
|
||||||
@ -53,24 +53,24 @@ func (f *fetcher[V]) Initial() (V, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
proxies, err := f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isLocal {
|
if !isLocal {
|
||||||
return getZero[V](), err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse local file error, fallback to remote
|
// parse local file error, fallback to remote
|
||||||
buf, err = f.vehicle.Read()
|
buf, err = f.vehicle.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies, err = f.parser(buf)
|
proxies, err = f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
isLocal = false
|
isLocal = false
|
||||||
@ -78,7 +78,7 @@ func (f *fetcher[V]) Initial() (V, error) {
|
|||||||
|
|
||||||
if f.vehicle.Type() != types.File && !isLocal {
|
if f.vehicle.Type() != types.File && !isLocal {
|
||||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
return getZero[V](), err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,28 +92,28 @@ func (f *fetcher[V]) Initial() (V, error) {
|
|||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Update() (V, 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 getZero[V](), false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
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)
|
os.Chtimes(f.vehicle.Path(), now, now)
|
||||||
return getZero[V](), true, nil
|
return nil, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
proxies, err := f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if f.vehicle.Type() != types.File {
|
if f.vehicle.Type() != types.File {
|
||||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
||||||
return getZero[V](), false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -123,14 +123,14 @@ func (f *fetcher[V]) Update() (V, bool, error) {
|
|||||||
return proxies, false, nil
|
return proxies, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) Destroy() error {
|
func (f *fetcher) Destroy() error {
|
||||||
if f.ticker != nil {
|
if f.ticker != nil {
|
||||||
f.done <- struct{}{}
|
f.done <- struct{}{}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fetcher[V]) pullLoop() {
|
func (f *fetcher) pullLoop() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-f.ticker.C:
|
case <-f.ticker.C:
|
||||||
@ -168,13 +168,13 @@ func safeWrite(path string, buf []byte) error {
|
|||||||
return os.WriteFile(path, buf, fileMode)
|
return os.WriteFile(path, buf, fileMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser parser[V], onUpdate func(V)) *fetcher[V] {
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &fetcher[V]{
|
return &fetcher{
|
||||||
name: name,
|
name: name,
|
||||||
ticker: ticker,
|
ticker: ticker,
|
||||||
vehicle: vehicle,
|
vehicle: vehicle,
|
||||||
@ -183,8 +183,3 @@ func newFetcher[V any](name string, interval time.Duration, vehicle types.Vehicl
|
|||||||
onUpdate: onUpdate,
|
onUpdate: onUpdate,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getZero[V any]() V {
|
|
||||||
var result V
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
@ -65,13 +65,8 @@ func (hc *HealthCheck) touch() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
proxies := hc.proxies
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range hc.proxies {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
@ -20,18 +20,15 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path"`
|
Path string `provider:"path"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
ForceCertVerify bool `provider:"force-cert-verify,omitempty"`
|
|
||||||
PrefixName string `provider:"prefix-name,omitempty"`
|
|
||||||
Header map[string][]string `provider:"header,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify bool) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
@ -39,11 +36,6 @@ func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify boo
|
|||||||
Lazy: true,
|
Lazy: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if forceCertVerify {
|
|
||||||
schema.ForceCertVerify = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := decoder.Decode(mapping, schema); err != nil {
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -61,12 +53,12 @@ func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify boo
|
|||||||
case "file":
|
case "file":
|
||||||
vehicle = NewFileVehicle(path)
|
vehicle = NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
vehicle = NewHTTPVehicle(schema.URL, path, schema.Header)
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
filter := schema.Filter
|
filter := schema.Filter
|
||||||
return NewProxySetProvider(name, interval, filter, vehicle, hc, schema.ForceCertVerify, schema.PrefixName)
|
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
@ -4,16 +4,16 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"github.com/dlclark/regexp2"
|
||||||
|
"math"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -24,16 +24,20 @@ type ProxySchema struct {
|
|||||||
Proxies []map[string]any `yaml:"proxies"`
|
Proxies []map[string]any `yaml:"proxies"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxySetProvider for auto gc
|
// for auto gc
|
||||||
type ProxySetProvider struct {
|
type ProxySetProvider struct {
|
||||||
*proxySetProvider
|
*proxySetProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*fetcher[[]C.Proxy]
|
*fetcher
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
providersInUse []types.ProxyProvider
|
version uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Version() uint {
|
||||||
|
return pp.version
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -42,7 +46,8 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.updatedAt,
|
//TODO maybe error because year value overflow
|
||||||
|
"updatedAt": pp.updatedAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,6 +74,10 @@ func (pp *proxySetProvider) Initial() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pp.onUpdate(elm)
|
pp.onUpdate(elm)
|
||||||
|
if pp.healthCheck.auto() {
|
||||||
|
go pp.healthCheck.process()
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,37 +97,75 @@ func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
|||||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
|
if pp.healthCheck.auto() {
|
||||||
for _, use := range pp.providersInUse {
|
go pp.healthCheck.check()
|
||||||
_ = use.Update()
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) RegisterProvidersInUse(providers ...types.ProxyProvider) {
|
|
||||||
pp.providersInUse = append(pp.providersInUse, providers...)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.fetcher.Destroy()
|
pd.fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck, forceCertVerify bool, prefixName string) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
filterReg, err := regexp.Compile(filter)
|
//filterReg, err := regexp.Compile(filter)
|
||||||
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if hc.auto() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
pd := &proxySetProvider{
|
pd := &proxySetProvider{
|
||||||
proxies: []C.Proxy{},
|
proxies: []C.Proxy{},
|
||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := newFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg, forceCertVerify, prefixName), proxiesOnUpdate(pd))
|
onUpdate := func(elm any) {
|
||||||
|
ret := elm.([]C.Proxy)
|
||||||
|
pd.setProxies(ret)
|
||||||
|
if pd.version == math.MaxUint {
|
||||||
|
pd.version = 0
|
||||||
|
} else {
|
||||||
|
pd.version++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesParseAndFilter := func(buf []byte) (any, error) {
|
||||||
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if schema.Proxies == nil {
|
||||||
|
return nil, errors.New("file must have a `proxies` field")
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for idx, mapping := range schema.Proxies {
|
||||||
|
name, ok := mapping["name"]
|
||||||
|
mat, _ := filterReg.FindStringMatch(name.(string))
|
||||||
|
if ok && len(filter) > 0 && mat == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
if len(filter) > 0 {
|
||||||
|
return nil, errors.New("doesn't match any proxy, please check your filter")
|
||||||
|
}
|
||||||
|
return nil, errors.New("file doesn't have any proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fetcher := newFetcher(name, interval, vehicle, proxiesParseAndFilter, onUpdate)
|
||||||
pd.fetcher = fetcher
|
pd.fetcher = fetcher
|
||||||
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
@ -126,7 +173,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CompatibleProvider for auto gc
|
// for auto gc
|
||||||
type CompatibleProvider struct {
|
type CompatibleProvider struct {
|
||||||
*compatibleProvider
|
*compatibleProvider
|
||||||
}
|
}
|
||||||
@ -135,6 +182,11 @@ type compatibleProvider struct {
|
|||||||
name string
|
name string
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
|
version uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Version() uint {
|
||||||
|
return cp.version
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -159,6 +211,10 @@ func (cp *compatibleProvider) Update() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Initial() error {
|
func (cp *compatibleProvider) Initial() error {
|
||||||
|
if cp.healthCheck.auto() {
|
||||||
|
go cp.healthCheck.process()
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -188,10 +244,6 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
return nil, errors.New("provider need one proxy at least")
|
return nil, errors.New("provider need one proxy at least")
|
||||||
}
|
}
|
||||||
|
|
||||||
if hc.auto() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
pd := &compatibleProvider{
|
pd := &compatibleProvider{
|
||||||
name: name,
|
name: name,
|
||||||
proxies: proxies,
|
proxies: proxies,
|
||||||
@ -202,145 +254,3 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyFilterProvider for filter provider
|
|
||||||
type ProxyFilterProvider struct {
|
|
||||||
*proxyFilterProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
type proxyFilterProvider struct {
|
|
||||||
name string
|
|
||||||
psd *ProxySetProvider
|
|
||||||
proxies []C.Proxy
|
|
||||||
filter *regexp.Regexp
|
|
||||||
healthCheck *HealthCheck
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]any{
|
|
||||||
"name": pf.Name(),
|
|
||||||
"type": pf.Type().String(),
|
|
||||||
"vehicleType": pf.VehicleType().String(),
|
|
||||||
"proxies": pf.Proxies(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Name() string {
|
|
||||||
return pf.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) HealthCheck() {
|
|
||||||
pf.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Update() error {
|
|
||||||
var proxies []C.Proxy
|
|
||||||
if pf.filter != nil {
|
|
||||||
for _, proxy := range pf.psd.Proxies() {
|
|
||||||
if !pf.filter.MatchString(proxy.Name()) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
proxies = pf.psd.Proxies()
|
|
||||||
}
|
|
||||||
|
|
||||||
pf.proxies = proxies
|
|
||||||
pf.healthCheck.setProxy(proxies)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Initial() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) VehicleType() types.VehicleType {
|
|
||||||
return pf.psd.VehicleType()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Type() types.ProviderType {
|
|
||||||
return types.Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Proxies() []C.Proxy {
|
|
||||||
return pf.proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) ProxiesWithTouch() []C.Proxy {
|
|
||||||
pf.healthCheck.touch()
|
|
||||||
return pf.Proxies()
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopProxyFilterProvider(pf *ProxyFilterProvider) {
|
|
||||||
pf.healthCheck.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewProxyFilterProvider(name string, psd *ProxySetProvider, hc *HealthCheck, filterRegx *regexp.Regexp) *ProxyFilterProvider {
|
|
||||||
pd := &proxyFilterProvider{
|
|
||||||
psd: psd,
|
|
||||||
name: name,
|
|
||||||
healthCheck: hc,
|
|
||||||
filter: filterRegx,
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = pd.Update()
|
|
||||||
|
|
||||||
if hc.auto() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
wrapper := &ProxyFilterProvider{pd}
|
|
||||||
runtime.SetFinalizer(wrapper, stopProxyFilterProvider)
|
|
||||||
return wrapper
|
|
||||||
}
|
|
||||||
|
|
||||||
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|
||||||
return func(elm []C.Proxy) {
|
|
||||||
pd.setProxies(elm)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, filterReg *regexp.Regexp, forceCertVerify bool, prefixName string) parser[[]C.Proxy] {
|
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
|
||||||
schema := &ProxySchema{}
|
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
|
||||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
|
||||||
if err1 != nil {
|
|
||||||
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
|
||||||
}
|
|
||||||
schema.Proxies = proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
if schema.Proxies == nil {
|
|
||||||
return nil, errors.New("file must have a `proxies` field")
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
|
||||||
for idx, mapping := range schema.Proxies {
|
|
||||||
if name, ok := mapping["name"]; ok && len(filter) > 0 && !filterReg.MatchString(name.(string)) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if prefixName != "" {
|
|
||||||
mapping["name"] = prefixName + mapping["name"].(string)
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping, forceCertVerify)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
|
||||||
}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
if len(filter) > 0 {
|
|
||||||
return nil, errors.New("doesn't match any proxy, please check your filter")
|
|
||||||
}
|
|
||||||
return nil, errors.New("file doesn't have any proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -2,6 +2,7 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"github.com/Dreamacro/clash/listener/inner"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -9,9 +10,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
netHttp "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -36,9 +35,8 @@ func NewFileVehicle(path string) *FileVehicle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type HTTPVehicle struct {
|
type HTTPVehicle struct {
|
||||||
url string
|
url string
|
||||||
path string
|
path string
|
||||||
header http.Header
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HTTPVehicle) Type() types.VehicleType {
|
func (h *HTTPVehicle) Type() types.VehicleType {
|
||||||
@ -59,23 +57,17 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
||||||
|
req.Header.Set("User-Agent", netHttp.UA)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.header != nil {
|
|
||||||
req.Header = h.header
|
|
||||||
}
|
|
||||||
|
|
||||||
if user := uri.User; user != nil {
|
if user := uri.User; user != nil {
|
||||||
password, _ := user.Password()
|
password, _ := user.Password()
|
||||||
req.SetBasicAuth(user.Username(), password)
|
req.SetBasicAuth(user.Username(), password)
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.UserAgent() == "" {
|
|
||||||
convert.SetUserAgent(req)
|
|
||||||
}
|
|
||||||
|
|
||||||
req = req.WithContext(ctx)
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
transport := &http.Transport{
|
transport := &http.Transport{
|
||||||
@ -84,24 +76,20 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
IdleConnTimeout: 90 * time.Second,
|
IdleConnTimeout: 90 * time.Second,
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: func(ctx context.Context, network, address string) (conn net.Conn, err error) {
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
conn, err = dialer.DialContext(ctx, network, address) // with direct
|
conn := inner.HandleTcp(address, uri.Hostname())
|
||||||
if err != nil {
|
return conn, nil
|
||||||
// fallback to tun if tun enabled
|
|
||||||
conn, err = (&net.Dialer{Timeout: C.DefaultTCPTimeout}).Dial(network, address)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{Transport: transport}
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
defer func() {
|
defer resp.Body.Close()
|
||||||
_ = resp.Body.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
buf, err := io.ReadAll(resp.Body)
|
buf, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -111,6 +99,6 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
return buf, nil
|
return buf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHTTPVehicle(url string, path string, header http.Header) *HTTPVehicle {
|
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
||||||
return &HTTPVehicle{url, path, header}
|
return &HTTPVehicle{url, path}
|
||||||
}
|
}
|
||||||
|
28
check_amd64.sh
Normal file
28
check_amd64.sh
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
flags=$(grep '^flags\b' </proc/cpuinfo | head -n 1)
|
||||||
|
flags=" ${flags#*:} "
|
||||||
|
|
||||||
|
has_flags () {
|
||||||
|
for flag; do
|
||||||
|
case "$flags" in
|
||||||
|
*" $flag "*) :;;
|
||||||
|
*) return 1;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
determine_level () {
|
||||||
|
level=0
|
||||||
|
has_flags lm cmov cx8 fpu fxsr mmx syscall sse2 || return 0
|
||||||
|
level=1
|
||||||
|
has_flags cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 || return 0
|
||||||
|
level=2
|
||||||
|
has_flags avx avx2 bmi1 bmi2 f16c fma abm movbe xsave || return 0
|
||||||
|
level=3
|
||||||
|
has_flags avx512f avx512bw avx512cd avx512dq avx512vl || return 0
|
||||||
|
level=4
|
||||||
|
}
|
||||||
|
|
||||||
|
determine_level
|
||||||
|
echo "Your CPU supports amd64-v$level"
|
||||||
|
return $level
|
2
common/cache/cache.go
vendored
2
common/cache/cache.go
vendored
@ -61,7 +61,7 @@ func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
|||||||
|
|
||||||
func (c *cache[K, V]) cleanup() {
|
func (c *cache[K, V]) cleanup() {
|
||||||
c.mapping.Range(func(k, v any) bool {
|
c.mapping.Range(func(k, v any) bool {
|
||||||
key := k
|
key := k.(string)
|
||||||
elm := v.(*element[V])
|
elm := v.(*element[V])
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
c.mapping.Delete(key)
|
c.mapping.Delete(key)
|
||||||
|
@ -1,303 +0,0 @@
|
|||||||
package cert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/sha1"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"crypto/x509/pkix"
|
|
||||||
"encoding/pem"
|
|
||||||
"math/big"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var currentSerialNumber = time.Now().Unix()
|
|
||||||
|
|
||||||
type Config struct {
|
|
||||||
ca *x509.Certificate
|
|
||||||
caPrivateKey *rsa.PrivateKey
|
|
||||||
|
|
||||||
roots *x509.CertPool
|
|
||||||
|
|
||||||
privateKey *rsa.PrivateKey
|
|
||||||
|
|
||||||
validity time.Duration
|
|
||||||
keyID []byte
|
|
||||||
organization string
|
|
||||||
|
|
||||||
certsStorage CertsStorage
|
|
||||||
}
|
|
||||||
|
|
||||||
type CertsStorage interface {
|
|
||||||
Get(key string) (*tls.Certificate, bool)
|
|
||||||
|
|
||||||
Set(key string, cert *tls.Certificate)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAuthority(name, organization string, validity time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
pub := privateKey.Public()
|
|
||||||
|
|
||||||
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
h := sha1.New()
|
|
||||||
_, err = h.Write(pkixPub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
keyID := h.Sum(nil)
|
|
||||||
|
|
||||||
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
|
||||||
|
|
||||||
tmpl := &x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(serial),
|
|
||||||
Subject: pkix.Name{
|
|
||||||
CommonName: name,
|
|
||||||
Organization: []string{organization},
|
|
||||||
},
|
|
||||||
SubjectKeyId: keyID,
|
|
||||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
NotBefore: time.Now().Add(-validity),
|
|
||||||
NotAfter: time.Now().Add(validity),
|
|
||||||
DNSNames: []string{name},
|
|
||||||
IsCA: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
raw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, privateKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
x509c, err := x509.ParseCertificate(raw)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return x509c, privateKey, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConfig(ca *x509.Certificate, caPrivateKey *rsa.PrivateKey) (*Config, error) {
|
|
||||||
roots := x509.NewCertPool()
|
|
||||||
roots.AddCert(ca)
|
|
||||||
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
pub := privateKey.Public()
|
|
||||||
|
|
||||||
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
h := sha1.New()
|
|
||||||
_, err = h.Write(pkixPub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
keyID := h.Sum(nil)
|
|
||||||
|
|
||||||
return &Config{
|
|
||||||
ca: ca,
|
|
||||||
caPrivateKey: caPrivateKey,
|
|
||||||
privateKey: privateKey,
|
|
||||||
keyID: keyID,
|
|
||||||
validity: time.Hour,
|
|
||||||
organization: "Clash",
|
|
||||||
certsStorage: NewDomainTrieCertsStorage(),
|
|
||||||
roots: roots,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) GetCA() *x509.Certificate {
|
|
||||||
return c.ca
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) SetOrganization(organization string) {
|
|
||||||
c.organization = organization
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) SetValidity(validity time.Duration) {
|
|
||||||
c.validity = validity
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) NewTLSConfigForHost(hostname string) *tls.Config {
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
|
||||||
host := clientHello.ServerName
|
|
||||||
if host == "" {
|
|
||||||
host = hostname
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.GetOrCreateCert(host)
|
|
||||||
},
|
|
||||||
NextProtos: []string{"http/1.1"},
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
|
|
||||||
return tlsConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) GetOrCreateCert(hostname string, ips ...net.IP) (*tls.Certificate, error) {
|
|
||||||
var leaf *x509.Certificate
|
|
||||||
tlsCertificate, ok := c.certsStorage.Get(hostname)
|
|
||||||
if ok {
|
|
||||||
leaf = tlsCertificate.Leaf
|
|
||||||
if _, err := leaf.Verify(x509.VerifyOptions{
|
|
||||||
DNSName: hostname,
|
|
||||||
Roots: c.roots,
|
|
||||||
}); err == nil {
|
|
||||||
return tlsCertificate, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
key = hostname
|
|
||||||
topHost = hostname
|
|
||||||
wildcardHost = "*." + hostname
|
|
||||||
dnsNames []string
|
|
||||||
)
|
|
||||||
|
|
||||||
if ip := net.ParseIP(hostname); ip != nil {
|
|
||||||
ips = append(ips, ip)
|
|
||||||
} else {
|
|
||||||
parts := strings.Split(hostname, ".")
|
|
||||||
l := len(parts)
|
|
||||||
|
|
||||||
if leaf != nil {
|
|
||||||
dnsNames = append(dnsNames, leaf.DNSNames...)
|
|
||||||
}
|
|
||||||
|
|
||||||
if l > 2 {
|
|
||||||
topIndex := l - 2
|
|
||||||
topHost = strings.Join(parts[topIndex:], ".")
|
|
||||||
|
|
||||||
for i := topIndex; i > 0; i-- {
|
|
||||||
wildcardHost = "*." + strings.Join(parts[i:], ".")
|
|
||||||
|
|
||||||
if i == topIndex && (len(dnsNames) == 0 || dnsNames[0] != topHost) {
|
|
||||||
dnsNames = append(dnsNames, topHost, wildcardHost)
|
|
||||||
} else if !hasDnsNames(dnsNames, wildcardHost) {
|
|
||||||
dnsNames = append(dnsNames, wildcardHost)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
dnsNames = append(dnsNames, topHost, wildcardHost)
|
|
||||||
}
|
|
||||||
|
|
||||||
key = "+." + topHost
|
|
||||||
}
|
|
||||||
|
|
||||||
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
|
||||||
|
|
||||||
tmpl := &x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(serial),
|
|
||||||
Subject: pkix.Name{
|
|
||||||
CommonName: topHost,
|
|
||||||
Organization: []string{c.organization},
|
|
||||||
},
|
|
||||||
SubjectKeyId: c.keyID,
|
|
||||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
NotBefore: time.Now().Add(-c.validity),
|
|
||||||
NotAfter: time.Now().Add(c.validity),
|
|
||||||
DNSNames: dnsNames,
|
|
||||||
IPAddresses: ips,
|
|
||||||
}
|
|
||||||
|
|
||||||
raw, err := x509.CreateCertificate(rand.Reader, tmpl, c.ca, c.privateKey.Public(), c.caPrivateKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
x509c, err := x509.ParseCertificate(raw)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsCertificate = &tls.Certificate{
|
|
||||||
Certificate: [][]byte{raw, c.ca.Raw},
|
|
||||||
PrivateKey: c.privateKey,
|
|
||||||
Leaf: x509c,
|
|
||||||
}
|
|
||||||
|
|
||||||
c.certsStorage.Set(key, tlsCertificate)
|
|
||||||
return tlsCertificate, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GenerateAndSave generate CA private key and CA certificate and dump them to file
|
|
||||||
func GenerateAndSave(caPath string, caKeyPath string) error {
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
tmpl := &x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(time.Now().Unix()),
|
|
||||||
Subject: pkix.Name{
|
|
||||||
Country: []string{"US"},
|
|
||||||
CommonName: "Clash Root CA",
|
|
||||||
Organization: []string{"Clash Trust Services"},
|
|
||||||
},
|
|
||||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
NotBefore: time.Now().Add(-(time.Hour * 24 * 60)),
|
|
||||||
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 25),
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
IsCA: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
caRaw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, privateKey.Public(), privateKey)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
caOut, err := os.OpenFile(caPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func(caOut *os.File) {
|
|
||||||
_ = caOut.Close()
|
|
||||||
}(caOut)
|
|
||||||
|
|
||||||
if err = pem.Encode(caOut, &pem.Block{Type: "CERTIFICATE", Bytes: caRaw}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
caKeyOut, err := os.OpenFile(caKeyPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func(caKeyOut *os.File) {
|
|
||||||
_ = caKeyOut.Close()
|
|
||||||
}(caKeyOut)
|
|
||||||
|
|
||||||
if err = pem.Encode(caKeyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func hasDnsNames(dnsNames []string, hostname string) bool {
|
|
||||||
for _, name := range dnsNames {
|
|
||||||
if name == hostname {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
@ -1,104 +0,0 @@
|
|||||||
package cert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCert(t *testing.T) {
|
|
||||||
ca, privateKey, err := NewAuthority("Clash ca", "Clash", 24*time.Hour)
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.NotNil(t, ca)
|
|
||||||
assert.NotNil(t, privateKey)
|
|
||||||
|
|
||||||
c, err := NewConfig(ca, privateKey)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
c.SetValidity(20 * time.Hour)
|
|
||||||
c.SetOrganization("Test Organization")
|
|
||||||
|
|
||||||
conf := c.NewTLSConfigForHost("example.org")
|
|
||||||
assert.Equal(t, []string{"http/1.1"}, conf.NextProtos)
|
|
||||||
assert.True(t, conf.InsecureSkipVerify)
|
|
||||||
|
|
||||||
// Test generating a certificate
|
|
||||||
clientHello := &tls.ClientHelloInfo{
|
|
||||||
ServerName: "example.org",
|
|
||||||
}
|
|
||||||
tlsCert, err := conf.GetCertificate(clientHello)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.NotNil(t, tlsCert)
|
|
||||||
|
|
||||||
// Assert certificate details
|
|
||||||
x509c := tlsCert.Leaf
|
|
||||||
assert.Equal(t, "example.org", x509c.Subject.CommonName)
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("abc.example.org"))
|
|
||||||
assert.Equal(t, []string{"Test Organization"}, x509c.Subject.Organization)
|
|
||||||
assert.NotNil(t, x509c.SubjectKeyId)
|
|
||||||
assert.True(t, x509c.BasicConstraintsValid)
|
|
||||||
assert.True(t, x509c.KeyUsage&x509.KeyUsageKeyEncipherment == x509.KeyUsageKeyEncipherment)
|
|
||||||
assert.True(t, x509c.KeyUsage&x509.KeyUsageDigitalSignature == x509.KeyUsageDigitalSignature)
|
|
||||||
assert.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, x509c.ExtKeyUsage)
|
|
||||||
assert.Equal(t, []string{"example.org", "*.example.org"}, x509c.DNSNames)
|
|
||||||
assert.True(t, x509c.NotBefore.Before(time.Now().Add(-2*time.Hour)))
|
|
||||||
assert.True(t, x509c.NotAfter.After(time.Now().Add(2*time.Hour)))
|
|
||||||
|
|
||||||
// Check that certificate is cached
|
|
||||||
tlsCert2, err := c.GetOrCreateCert("abc.example.org")
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.True(t, tlsCert == tlsCert2)
|
|
||||||
|
|
||||||
// Check that certificate is new
|
|
||||||
_, _ = c.GetOrCreateCert("a.b.c.d.e.f.g.h.i.j.example.org")
|
|
||||||
tlsCert3, err := c.GetOrCreateCert("m.k.l.example.org")
|
|
||||||
x509c = tlsCert3.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.False(t, tlsCert == tlsCert3)
|
|
||||||
assert.Equal(t, []string{"example.org", "*.example.org", "*.j.example.org", "*.i.j.example.org", "*.h.i.j.example.org", "*.g.h.i.j.example.org", "*.f.g.h.i.j.example.org", "*.e.f.g.h.i.j.example.org", "*.d.e.f.g.h.i.j.example.org", "*.c.d.e.f.g.h.i.j.example.org", "*.b.c.d.e.f.g.h.i.j.example.org", "*.l.example.org", "*.k.l.example.org"}, x509c.DNSNames)
|
|
||||||
|
|
||||||
// Check that certificate is cached
|
|
||||||
tlsCert4, err := c.GetOrCreateCert("xyz.example.org")
|
|
||||||
x509c = tlsCert4.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.True(t, tlsCert3 == tlsCert4)
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("jkf.example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("n.j.example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("c.i.j.example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("m.l.example.org"))
|
|
||||||
assert.Error(t, x509c.VerifyHostname("m.l.jkf.example.org"))
|
|
||||||
|
|
||||||
// Check the certificate for an IP
|
|
||||||
tlsCertForIP, err := c.GetOrCreateCert("192.168.0.1")
|
|
||||||
x509c = tlsCertForIP.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, 1, len(x509c.IPAddresses))
|
|
||||||
assert.True(t, net.ParseIP("192.168.0.1").Equal(x509c.IPAddresses[0]))
|
|
||||||
|
|
||||||
// Check that certificate is cached
|
|
||||||
tlsCertForIP2, err := c.GetOrCreateCert("192.168.0.1")
|
|
||||||
x509c = tlsCertForIP2.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.True(t, tlsCertForIP == tlsCertForIP2)
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("192.168.0.1"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGenerateAndSave(t *testing.T) {
|
|
||||||
caPath := "ca.crt"
|
|
||||||
caKeyPath := "ca.key"
|
|
||||||
|
|
||||||
err := GenerateAndSave(caPath, caKeyPath)
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
_ = os.Remove(caPath)
|
|
||||||
_ = os.Remove(caKeyPath)
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
package cert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DomainTrieCertsStorage cache wildcard certificates
|
|
||||||
type DomainTrieCertsStorage struct {
|
|
||||||
certsCache *trie.DomainTrie[*tls.Certificate]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get gets the certificate from the storage
|
|
||||||
func (c *DomainTrieCertsStorage) Get(key string) (*tls.Certificate, bool) {
|
|
||||||
ca := c.certsCache.Search(key)
|
|
||||||
if ca == nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return ca.Data, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set saves the certificate to the storage
|
|
||||||
func (c *DomainTrieCertsStorage) Set(key string, cert *tls.Certificate) {
|
|
||||||
_ = c.certsCache.Insert(key, cert)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDomainTrieCertsStorage() *DomainTrieCertsStorage {
|
|
||||||
return &DomainTrieCertsStorage{
|
|
||||||
certsCache: trie.New[*tls.Certificate](),
|
|
||||||
}
|
|
||||||
}
|
|
@ -14,8 +14,9 @@ func ExecCmd(cmdStr string) (string, error) {
|
|||||||
cmd = exec.Command(args[0])
|
cmd = exec.Command(args[0])
|
||||||
} else {
|
} else {
|
||||||
cmd = exec.Command(args[0], args[1:]...)
|
cmd = exec.Command(args[0], args[1:]...)
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
|
prepareBackgroundCommand(cmd)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||||
|
11
common/cmd/cmd_other.go
Normal file
11
common/cmd/cmd_other.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
)
|
||||||
|
|
||||||
|
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||||
|
|
||||||
|
}
|
12
common/cmd/cmd_windows.go
Normal file
12
common/cmd/cmd_windows.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
||||||
|
}
|
56
common/collections/stack.go
Normal file
56
common/collections/stack.go
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package collections
|
||||||
|
|
||||||
|
import "sync"
|
||||||
|
|
||||||
|
type (
|
||||||
|
stack struct {
|
||||||
|
top *node
|
||||||
|
length int
|
||||||
|
lock *sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
node struct {
|
||||||
|
value interface{}
|
||||||
|
prev *node
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewStack Create a new stack
|
||||||
|
func NewStack() *stack {
|
||||||
|
return &stack{nil, 0, &sync.RWMutex{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len Return the number of items in the stack
|
||||||
|
func (this *stack) Len() int {
|
||||||
|
return this.length
|
||||||
|
}
|
||||||
|
|
||||||
|
// Peek View the top item on the stack
|
||||||
|
func (this *stack) Peek() interface{} {
|
||||||
|
if this.length == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return this.top.value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pop the top item of the stack and return it
|
||||||
|
func (this *stack) Pop() interface{} {
|
||||||
|
this.lock.Lock()
|
||||||
|
defer this.lock.Unlock()
|
||||||
|
if this.length == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n := this.top
|
||||||
|
this.top = n.prev
|
||||||
|
this.length--
|
||||||
|
return n.value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push a value onto the top of the stack
|
||||||
|
func (this *stack) Push(value interface{}) {
|
||||||
|
this.lock.Lock()
|
||||||
|
defer this.lock.Unlock()
|
||||||
|
n := &node{value, this.top}
|
||||||
|
this.top = n
|
||||||
|
this.length++
|
||||||
|
}
|
@ -1,344 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var enc = base64.StdEncoding
|
|
||||||
|
|
||||||
func DecodeBase64(buf []byte) ([]byte, error) {
|
|
||||||
dBuf := make([]byte, enc.DecodedLen(len(buf)))
|
|
||||||
n, err := enc.Decode(dBuf, buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dBuf[:n], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeBase64StringToString decode base64 string to string
|
|
||||||
func DecodeBase64StringToString(s string) (string, error) {
|
|
||||||
dBuf, err := enc.DecodeString(s)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(dBuf), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|
||||||
data, err := DecodeBase64(buf)
|
|
||||||
if err != nil {
|
|
||||||
data = buf
|
|
||||||
}
|
|
||||||
|
|
||||||
arr := strings.Split(string(data), "\n")
|
|
||||||
|
|
||||||
proxies := make([]map[string]any, 0, len(arr))
|
|
||||||
names := make(map[string]int, 200)
|
|
||||||
|
|
||||||
for _, line := range arr {
|
|
||||||
line = strings.TrimRight(line, " \r")
|
|
||||||
if line == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
scheme, body, found := strings.Cut(line, "://")
|
|
||||||
if !found {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
scheme = strings.ToLower(scheme)
|
|
||||||
switch scheme {
|
|
||||||
case "trojan":
|
|
||||||
urlTrojan, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
q := urlTrojan.Query()
|
|
||||||
|
|
||||||
name := uniqueName(names, urlTrojan.Fragment)
|
|
||||||
trojan := make(map[string]any, 20)
|
|
||||||
|
|
||||||
trojan["name"] = name
|
|
||||||
trojan["type"] = scheme
|
|
||||||
trojan["server"] = urlTrojan.Hostname()
|
|
||||||
trojan["port"] = urlTrojan.Port()
|
|
||||||
trojan["password"] = urlTrojan.User.Username()
|
|
||||||
trojan["udp"] = true
|
|
||||||
trojan["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
sni := q.Get("sni")
|
|
||||||
if sni != "" {
|
|
||||||
trojan["sni"] = sni
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(q.Get("type"))
|
|
||||||
if network != "" {
|
|
||||||
trojan["network"] = network
|
|
||||||
}
|
|
||||||
|
|
||||||
if network == "ws" {
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
|
|
||||||
headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
|
|
||||||
wsOpts["path"] = q.Get("path")
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
trojan["ws-opts"] = wsOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, trojan)
|
|
||||||
case "vmess":
|
|
||||||
dcBuf, err := enc.DecodeString(body)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonDc := json.NewDecoder(bytes.NewReader(dcBuf))
|
|
||||||
values := make(map[string]any, 20)
|
|
||||||
|
|
||||||
if jsonDc.Decode(&values) != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
name := uniqueName(names, values["ps"].(string))
|
|
||||||
vmess := make(map[string]any, 20)
|
|
||||||
|
|
||||||
vmess["name"] = name
|
|
||||||
vmess["type"] = scheme
|
|
||||||
vmess["server"] = values["add"]
|
|
||||||
vmess["port"] = values["port"]
|
|
||||||
vmess["uuid"] = values["id"]
|
|
||||||
vmess["alterId"] = values["aid"]
|
|
||||||
vmess["cipher"] = "auto"
|
|
||||||
vmess["udp"] = true
|
|
||||||
vmess["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
host := values["host"]
|
|
||||||
network := strings.ToLower(values["net"].(string))
|
|
||||||
|
|
||||||
vmess["network"] = network
|
|
||||||
|
|
||||||
tls := strings.ToLower(values["tls"].(string))
|
|
||||||
if tls != "" && tls != "0" && tls != "null" {
|
|
||||||
if host != nil {
|
|
||||||
vmess["servername"] = host
|
|
||||||
}
|
|
||||||
vmess["tls"] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if network == "ws" {
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
|
|
||||||
headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
|
|
||||||
if values["path"] != nil {
|
|
||||||
wsOpts["path"] = values["path"]
|
|
||||||
}
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
vmess["ws-opts"] = wsOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, vmess)
|
|
||||||
case "ss":
|
|
||||||
urlSS, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
name := uniqueName(names, urlSS.Fragment)
|
|
||||||
port := urlSS.Port()
|
|
||||||
|
|
||||||
if port == "" {
|
|
||||||
dcBuf, err := enc.DecodeString(urlSS.Host)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
urlSS, err = url.Parse("ss://" + string(dcBuf))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
cipher = urlSS.User.Username()
|
|
||||||
password string
|
|
||||||
)
|
|
||||||
|
|
||||||
if password, found = urlSS.User.Password(); !found {
|
|
||||||
dcBuf, err := enc.DecodeString(cipher)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
|
||||||
if !found {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ss := make(map[string]any, 20)
|
|
||||||
|
|
||||||
ss["name"] = name
|
|
||||||
ss["type"] = scheme
|
|
||||||
ss["server"] = urlSS.Hostname()
|
|
||||||
ss["port"] = urlSS.Port()
|
|
||||||
ss["cipher"] = cipher
|
|
||||||
ss["password"] = password
|
|
||||||
ss["udp"] = true
|
|
||||||
|
|
||||||
proxies = append(proxies, ss)
|
|
||||||
case "ssr":
|
|
||||||
dcBuf, err := enc.DecodeString(body)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// ssr://host:port:protocol:method:obfs:urlsafebase64pass/?obfsparam=urlsafebase64&protoparam=&remarks=urlsafebase64&group=urlsafebase64&udpport=0&uot=1
|
|
||||||
|
|
||||||
before, after, ok := strings.Cut(string(dcBuf), "/?")
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeArr := strings.Split(before, ":")
|
|
||||||
|
|
||||||
if len(beforeArr) != 6 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
host := beforeArr[0]
|
|
||||||
port := beforeArr[1]
|
|
||||||
protocol := beforeArr[2]
|
|
||||||
method := beforeArr[3]
|
|
||||||
obfs := beforeArr[4]
|
|
||||||
password := decodeUrlSafe(urlSafe(beforeArr[5]))
|
|
||||||
|
|
||||||
query, err := url.ParseQuery(urlSafe(after))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
remarks := decodeUrlSafe(query.Get("remarks"))
|
|
||||||
name := uniqueName(names, remarks)
|
|
||||||
|
|
||||||
obfsParam := decodeUrlSafe(query.Get("obfsparam"))
|
|
||||||
protocolParam := query.Get("protoparam")
|
|
||||||
|
|
||||||
ssr := make(map[string]any, 20)
|
|
||||||
|
|
||||||
ssr["name"] = name
|
|
||||||
ssr["type"] = scheme
|
|
||||||
ssr["server"] = host
|
|
||||||
ssr["port"] = port
|
|
||||||
ssr["cipher"] = method
|
|
||||||
ssr["password"] = password
|
|
||||||
ssr["obfs"] = obfs
|
|
||||||
ssr["protocol"] = protocol
|
|
||||||
ssr["udp"] = true
|
|
||||||
|
|
||||||
if obfsParam != "" {
|
|
||||||
ssr["obfs-param"] = obfsParam
|
|
||||||
}
|
|
||||||
|
|
||||||
if protocolParam != "" {
|
|
||||||
ssr["protocol-param"] = protocolParam
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, ssr)
|
|
||||||
case "vless":
|
|
||||||
urlVless, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
q := urlVless.Query()
|
|
||||||
|
|
||||||
name := uniqueName(names, urlVless.Fragment)
|
|
||||||
vless := make(map[string]any, 20)
|
|
||||||
|
|
||||||
vless["name"] = name
|
|
||||||
vless["type"] = scheme
|
|
||||||
vless["server"] = urlVless.Hostname()
|
|
||||||
vless["port"] = urlVless.Port()
|
|
||||||
vless["uuid"] = urlVless.User.Username()
|
|
||||||
vless["udp"] = true
|
|
||||||
vless["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
sni := q.Get("sni")
|
|
||||||
if sni != "" {
|
|
||||||
vless["servername"] = sni
|
|
||||||
}
|
|
||||||
|
|
||||||
flow := strings.ToLower(q.Get("flow"))
|
|
||||||
if flow != "" {
|
|
||||||
vless["flow"] = flow
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(q.Get("type"))
|
|
||||||
if network != "" {
|
|
||||||
vless["network"] = network
|
|
||||||
}
|
|
||||||
|
|
||||||
if network == "ws" {
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
|
|
||||||
headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
|
|
||||||
wsOpts["path"] = q.Get("path")
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
vless["ws-opts"] = wsOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, vless)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, fmt.Errorf("convert v2ray subscribe error: format invalid")
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func urlSafe(data string) string {
|
|
||||||
return strings.ReplaceAll(strings.ReplaceAll(data, "+", "-"), "/", "_")
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeUrlSafe(data string) string {
|
|
||||||
dcBuf, err := base64.URLEncoding.DecodeString(data)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(dcBuf)
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueName(names map[string]int, name string) string {
|
|
||||||
if index, ok := names[name]; ok {
|
|
||||||
index++
|
|
||||||
names[name] = index
|
|
||||||
name = name + "-" + fmt.Sprintf("%02d", index)
|
|
||||||
} else {
|
|
||||||
index = 0
|
|
||||||
names[name] = index
|
|
||||||
}
|
|
||||||
return name
|
|
||||||
}
|
|
@ -1,313 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
|
||||||
"-cdn.aliyuncs.com",
|
|
||||||
".alicdn.com",
|
|
||||||
".pan.baidu.com",
|
|
||||||
".tbcache.com",
|
|
||||||
".aliyuncdn.com",
|
|
||||||
".vod.miguvideo.com",
|
|
||||||
".cibntv.net",
|
|
||||||
".myqcloud.com",
|
|
||||||
".smtcdns.com",
|
|
||||||
".alikunlun.com",
|
|
||||||
".smtcdns.net",
|
|
||||||
".apcdns.net",
|
|
||||||
".cdn-go.cn",
|
|
||||||
".cdntip.com",
|
|
||||||
".cdntips.com",
|
|
||||||
".alidayu.com",
|
|
||||||
".alidns.com",
|
|
||||||
".cdngslb.com",
|
|
||||||
".mxhichina.com",
|
|
||||||
".alibabadns.com",
|
|
||||||
}
|
|
||||||
|
|
||||||
var userAgents = []string{
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; Moto C Build/NRD90M.059) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J120M Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; Moto G (5) Build/NPPS25.137-93-14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; CAM-L03 Build/HUAWEICAM-L03) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Datanyze; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J111M Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J700M Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Slackware/Chrome/12.0.742.100 Safari/534.30",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; WAS-LX3 Build/HUAWEIWAS-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.1805 Safari/537.36 MVisionPlayer/1.0.0.0",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX3 Build/HUAWEITRT-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1610 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 4.4.2; de-de; SAMSUNG GT-I9195 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; ANE-LX3 Build/HUAWEIANE-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; U; Linux i586; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J500M Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1606 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1; vivo 1716 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; MYA-L22 Build/HUAWEIMYA-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1; A1601 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX2 Build/HUAWEITRT-LX2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; CAM-L21 Build/HUAWEICAM-L21; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.3 Safari/534.24",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4X Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 4.4.2; SM-G7102 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1; HUAWEI CUN-L22 Build/HUAWEICUN-L22; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1.1; A37fw Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-J730GM Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi Note 5A Build/N2G47H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Unknown; Linux) AppleWebKit/538.1 (KHTML, like Gecko) Chrome/v1.0.0 Safari/538.1",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; BLL-L22 Build/HUAWEIBLL-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-J710F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1.1; CPH1723 Build/N6F26Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3 Build/HUAWEIFIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1; Mi A1 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 MVisionPlayer/1.0.0.0",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1; A37f Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; CPH1607 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; vivo 1603 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4A Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.116 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1713 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
hostsLen = len(hostsSuffix)
|
|
||||||
uaLen = len(userAgents)
|
|
||||||
)
|
|
||||||
|
|
||||||
func RandHost() string {
|
|
||||||
id, _ := uuid.NewV4()
|
|
||||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
|
||||||
base = strings.ReplaceAll(base, "-", "")
|
|
||||||
base = strings.ReplaceAll(base, "_", "")
|
|
||||||
buf := []byte(base)
|
|
||||||
prefix := string(buf[:3]) + "---"
|
|
||||||
prefix += string(buf[6:8]) + "-"
|
|
||||||
prefix += string(buf[len(buf)-8:])
|
|
||||||
|
|
||||||
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
|
||||||
}
|
|
||||||
|
|
||||||
func RandUserAgent() string {
|
|
||||||
return userAgents[rand.Intn(uaLen)]
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetUserAgent(req *http.Request) {
|
|
||||||
userAgent := RandUserAgent()
|
|
||||||
req.Header.Set("User-Agent", userAgent)
|
|
||||||
}
|
|
5
common/net/http.go
Normal file
5
common/net/http.go
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
const (
|
||||||
|
UA = "Clash"
|
||||||
|
)
|
@ -12,28 +12,19 @@ import (
|
|||||||
func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
ch := make(chan error)
|
ch := make(chan error)
|
||||||
|
|
||||||
tcpKeepAlive(leftConn)
|
|
||||||
tcpKeepAlive(rightConn)
|
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
_ = pool.Put(buf)
|
pool.Put(buf)
|
||||||
_ = leftConn.SetReadDeadline(time.Now())
|
leftConn.SetReadDeadline(time.Now())
|
||||||
ch <- err
|
ch <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
_, _ = io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
_ = pool.Put(buf)
|
pool.Put(buf)
|
||||||
_ = rightConn.SetReadDeadline(time.Now())
|
rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
<-ch
|
||||||
}
|
}
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
|
||||||
_ = tcp.SetKeepAlive(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
46
common/net/tcpip.go
Normal file
46
common/net/tcpip.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SplitNetworkType(s string) (string, string, error) {
|
||||||
|
var (
|
||||||
|
shecme string
|
||||||
|
hostPort string
|
||||||
|
)
|
||||||
|
result := strings.Split(s, "://")
|
||||||
|
if len(result) == 2 {
|
||||||
|
shecme = result[0]
|
||||||
|
hostPort = result[1]
|
||||||
|
} else if len(result) == 1 {
|
||||||
|
hostPort = result[0]
|
||||||
|
} else {
|
||||||
|
return "", "", fmt.Errorf("tcp/udp style error")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(shecme) == 0 {
|
||||||
|
shecme = "udp"
|
||||||
|
}
|
||||||
|
|
||||||
|
if shecme != "tcp" && shecme != "udp" {
|
||||||
|
return "", "", fmt.Errorf("scheme should be tcp:// or udp://")
|
||||||
|
} else {
|
||||||
|
return shecme, hostPort, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
||||||
|
temp := s
|
||||||
|
hasPort = true
|
||||||
|
|
||||||
|
if !strings.Contains(s, ":") && !strings.Contains(s, "]:") {
|
||||||
|
temp += ":0"
|
||||||
|
hasPort = false
|
||||||
|
}
|
||||||
|
|
||||||
|
host, port, err = net.SplitHostPort(temp)
|
||||||
|
return
|
||||||
|
}
|
@ -52,8 +52,8 @@ func (alloc *Allocator) Put(buf []byte) error {
|
|||||||
return errors.New("allocator Put() incorrect buffer size")
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
}
|
}
|
||||||
|
|
||||||
//nolint
|
|
||||||
//lint:ignore SA6002 ignore temporarily
|
//lint:ignore SA6002 ignore temporarily
|
||||||
|
//nolint
|
||||||
alloc.buffers[bits].Put(buf)
|
alloc.buffers[bits].Put(buf)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -25,6 +25,7 @@ type Result[T any] struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do single.Do likes sync.singleFlight
|
// Do single.Do likes sync.singleFlight
|
||||||
|
//lint:ignore ST1008 it likes sync.singleFlight
|
||||||
func (s *Single[T]) Do(fn func() (T, error)) (v T, err error, shared bool) {
|
func (s *Single[T]) Do(fn func() (T, error)) (v T, err error, shared bool) {
|
||||||
s.mux.Lock()
|
s.mux.Lock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
@ -31,7 +31,7 @@ func NewDecoder(option Option) *Decoder {
|
|||||||
// Decode transform a map[string]any to a struct
|
// Decode transform a map[string]any to a struct
|
||||||
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||||
return fmt.Errorf("Decode must recive a ptr struct")
|
return fmt.Errorf("decode must recive a ptr struct")
|
||||||
}
|
}
|
||||||
t := reflect.TypeOf(dst).Elem()
|
t := reflect.TypeOf(dst).Elem()
|
||||||
v := reflect.ValueOf(dst).Elem()
|
v := reflect.ValueOf(dst).Elem()
|
||||||
@ -159,19 +159,9 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
for valSlice.Len() <= i {
|
for valSlice.Len() <= i {
|
||||||
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
||||||
}
|
}
|
||||||
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)
|
currentField := valSlice.Index(i)
|
||||||
|
|
||||||
|
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
||||||
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -301,7 +291,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
field reflect.StructField
|
field reflect.StructField
|
||||||
val reflect.Value
|
val reflect.Value
|
||||||
}
|
}
|
||||||
fields := []field{}
|
var fields []field
|
||||||
for len(structs) > 0 {
|
for len(structs) > 0 {
|
||||||
structVal := structs[0]
|
structVal := structs[0]
|
||||||
structs = structs[1:]
|
structs = structs[1:]
|
||||||
|
@ -137,45 +137,3 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_SliceNilValue(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"foo": 1,
|
|
||||||
"bar": []any{"bar", nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
goal := &BazSlice{
|
|
||||||
Foo: 1,
|
|
||||||
Bar: []string{"bar", ""},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &BazSlice{}
|
|
||||||
err := weakTypeDecoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, goal.Bar, s.Bar)
|
|
||||||
|
|
||||||
s = &BazSlice{}
|
|
||||||
err = decoder.Decode(rawMap, s)
|
|
||||||
assert.NotNil(t, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Bar []map[string]any `test:"bar"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Nil(t, s.Bar[1])
|
|
||||||
|
|
||||||
ss := &struct {
|
|
||||||
Bar []Baz `test:"bar"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err = decoder.Decode(rawMap, ss)
|
|
||||||
assert.NotNil(t, err)
|
|
||||||
}
|
|
||||||
|
44
common/utils/range.go
Normal file
44
common/utils/range.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"golang.org/x/exp/constraints"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Range[T constraints.Ordered] struct {
|
||||||
|
start T
|
||||||
|
end T
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRange[T constraints.Ordered](start, end T) *Range[T] {
|
||||||
|
if start > end {
|
||||||
|
return &Range[T]{
|
||||||
|
start: end,
|
||||||
|
end: start,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Range[T]{
|
||||||
|
start: start,
|
||||||
|
end: end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) Contains(t T) bool {
|
||||||
|
return t >= r.start && t <= r.end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) LeftContains(t T) bool {
|
||||||
|
return t >= r.start && t < r.end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) RightContains(t T) bool {
|
||||||
|
return t > r.start && t <= r.end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) Start() T {
|
||||||
|
return r.start
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) End() T {
|
||||||
|
return r.end
|
||||||
|
}
|
@ -3,12 +3,21 @@ package dialer
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
dialMux sync.Mutex
|
||||||
|
actualSingleDialContext = singleDialContext
|
||||||
|
actualDualStackDialContext = dualStackDialContext
|
||||||
|
DisableIPv6 = false
|
||||||
|
)
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
@ -25,33 +34,9 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
host, port, err := net.SplitHostPort(address)
|
return actualSingleDialContext(ctx, network, address, opt)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ip netip.Addr
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialContext(ctx, network, ip, port, opt)
|
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return dualStackDialContext(ctx, network, address, opt)
|
return actualDualStackDialContext(ctx, network, address, opt)
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("network invalid")
|
return nil, errors.New("network invalid")
|
||||||
}
|
}
|
||||||
@ -89,6 +74,19 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SetDial(concurrent bool) {
|
||||||
|
dialMux.Lock()
|
||||||
|
if concurrent {
|
||||||
|
actualSingleDialContext = concurrentSingleDialContext
|
||||||
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
|
} else {
|
||||||
|
actualSingleDialContext = singleDialContext
|
||||||
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
|
}
|
||||||
|
|
||||||
|
dialMux.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
dialer := &net.Dialer{}
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
@ -100,6 +98,10 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if DisableIPv6 && destination.Is6() {
|
||||||
|
return nil, fmt.Errorf("IPv6 is diabled, dialer cancel")
|
||||||
|
}
|
||||||
|
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -183,3 +185,130 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
|
|
||||||
return nil, errors.New("never touched")
|
return nil, errors.New("never touched")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
|
||||||
|
if opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIP(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
returned := make(chan struct{})
|
||||||
|
defer close(returned)
|
||||||
|
|
||||||
|
type dialResult struct {
|
||||||
|
ip netip.Addr
|
||||||
|
net.Conn
|
||||||
|
error
|
||||||
|
resolved bool
|
||||||
|
}
|
||||||
|
|
||||||
|
results := make(chan dialResult)
|
||||||
|
|
||||||
|
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
||||||
|
result := dialResult{ip: ip}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
select {
|
||||||
|
case results <- result:
|
||||||
|
case <-returned:
|
||||||
|
if result.Conn != nil {
|
||||||
|
result.Conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
v := "4"
|
||||||
|
if ip.Is6() {
|
||||||
|
v = "6"
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Conn, result.error = dialContext(ctx, network+v, ip, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ip := range ips {
|
||||||
|
go tcpRacer(ctx, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
connCount := len(ips)
|
||||||
|
for res := range results {
|
||||||
|
connCount--
|
||||||
|
if res.error == nil {
|
||||||
|
return res.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if connCount == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New("all ip tcp shake hands failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ip netip.Addr
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialContext(ctx, network, ip, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
if !opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if !opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPv6(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
@ -3,6 +3,7 @@ package geodata
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
@ -14,7 +15,7 @@ type loader struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
||||||
return l.LoadGeoSiteWithAttr("geosite.dat", list)
|
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
||||||
@ -58,7 +59,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||||
return l.LoadIP("geoip.dat", country)
|
return l.LoadIP(C.GeoipName, country)
|
||||||
}
|
}
|
||||||
|
|
||||||
var loaders map[string]func() LoaderImplementation
|
var loaders map[string]func() LoaderImplementation
|
||||||
|
@ -8,7 +8,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -33,7 +32,7 @@ func (g GeoIPCache) Set(key string, value *router.GeoIP) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (g GeoIPCache) Unmarshal(filename, code string) (*router.GeoIP, error) {
|
func (g GeoIPCache) Unmarshal(filename, code string) (*router.GeoIP, error) {
|
||||||
asset := C.Path.Resolve(filename)
|
asset := C.Path.GetAssetLocation(filename)
|
||||||
idx := strings.ToLower(asset + ":" + code)
|
idx := strings.ToLower(asset + ":" + code)
|
||||||
if g.Has(idx) {
|
if g.Has(idx) {
|
||||||
return g.Get(idx), nil
|
return g.Get(idx), nil
|
||||||
@ -98,7 +97,7 @@ func (g GeoSiteCache) Set(key string, value *router.GeoSite) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error) {
|
func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error) {
|
||||||
asset := C.Path.Resolve(filename)
|
asset := C.Path.GetAssetLocation(filename)
|
||||||
idx := strings.ToLower(asset + ":" + code)
|
idx := strings.ToLower(asset + ":" + code)
|
||||||
if g.Has(idx) {
|
if g.Has(idx) {
|
||||||
return g.Get(idx), nil
|
return g.Get(idx), nil
|
||||||
|
@ -1,7 +1,10 @@
|
|||||||
package router
|
package router
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/strmatcher"
|
"github.com/Dreamacro/clash/component/geodata/strmatcher"
|
||||||
@ -69,3 +72,279 @@ func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
|||||||
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
||||||
return len(m.matchers.Match(strings.ToLower(domain))) > 0
|
return len(m.matchers.Match(strings.ToLower(domain))) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CIDRList is an alias of []*CIDR to provide sort.Interface.
|
||||||
|
type CIDRList []*CIDR
|
||||||
|
|
||||||
|
// Len implements sort.Interface.
|
||||||
|
func (l *CIDRList) Len() int {
|
||||||
|
return len(*l)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Less implements sort.Interface.
|
||||||
|
func (l *CIDRList) Less(i int, j int) bool {
|
||||||
|
ci := (*l)[i]
|
||||||
|
cj := (*l)[j]
|
||||||
|
|
||||||
|
if len(ci.Ip) < len(cj.Ip) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(ci.Ip) > len(cj.Ip) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for k := 0; k < len(ci.Ip); k++ {
|
||||||
|
if ci.Ip[k] < cj.Ip[k] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if ci.Ip[k] > cj.Ip[k] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ci.Prefix < cj.Prefix
|
||||||
|
}
|
||||||
|
|
||||||
|
// Swap implements sort.Interface.
|
||||||
|
func (l *CIDRList) Swap(i int, j int) {
|
||||||
|
(*l)[i], (*l)[j] = (*l)[j], (*l)[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
type ipv6 struct {
|
||||||
|
a uint64
|
||||||
|
b uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
type GeoIPMatcher struct {
|
||||||
|
countryCode string
|
||||||
|
reverseMatch bool
|
||||||
|
ip4 []uint32
|
||||||
|
prefix4 []uint8
|
||||||
|
ip6 []ipv6
|
||||||
|
prefix6 []uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalize4(ip uint32, prefix uint8) uint32 {
|
||||||
|
return (ip >> (32 - prefix)) << (32 - prefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalize6(ip ipv6, prefix uint8) ipv6 {
|
||||||
|
if prefix <= 64 {
|
||||||
|
ip.a = (ip.a >> (64 - prefix)) << (64 - prefix)
|
||||||
|
ip.b = 0
|
||||||
|
} else {
|
||||||
|
ip.b = (ip.b >> (128 - prefix)) << (128 - prefix)
|
||||||
|
}
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *GeoIPMatcher) Init(cidrs []*CIDR) error {
|
||||||
|
ip4Count := 0
|
||||||
|
ip6Count := 0
|
||||||
|
|
||||||
|
for _, cidr := range cidrs {
|
||||||
|
ip := cidr.Ip
|
||||||
|
switch len(ip) {
|
||||||
|
case 4:
|
||||||
|
ip4Count++
|
||||||
|
case 16:
|
||||||
|
ip6Count++
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unexpect ip length: %d", len(ip))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cidrList := CIDRList(cidrs)
|
||||||
|
sort.Sort(&cidrList)
|
||||||
|
|
||||||
|
m.ip4 = make([]uint32, 0, ip4Count)
|
||||||
|
m.prefix4 = make([]uint8, 0, ip4Count)
|
||||||
|
m.ip6 = make([]ipv6, 0, ip6Count)
|
||||||
|
m.prefix6 = make([]uint8, 0, ip6Count)
|
||||||
|
|
||||||
|
for _, cidr := range cidrs {
|
||||||
|
ip := cidr.Ip
|
||||||
|
prefix := uint8(cidr.Prefix)
|
||||||
|
switch len(ip) {
|
||||||
|
case 4:
|
||||||
|
m.ip4 = append(m.ip4, normalize4(binary.BigEndian.Uint32(ip), prefix))
|
||||||
|
m.prefix4 = append(m.prefix4, prefix)
|
||||||
|
case 16:
|
||||||
|
ip6 := ipv6{
|
||||||
|
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||||
|
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||||
|
}
|
||||||
|
ip6 = normalize6(ip6, prefix)
|
||||||
|
|
||||||
|
m.ip6 = append(m.ip6, ip6)
|
||||||
|
m.prefix6 = append(m.prefix6, prefix)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *GeoIPMatcher) SetReverseMatch(isReverseMatch bool) {
|
||||||
|
m.reverseMatch = isReverseMatch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *GeoIPMatcher) match4(ip uint32) bool {
|
||||||
|
if len(m.ip4) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip < m.ip4[0] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
size := uint32(len(m.ip4))
|
||||||
|
l := uint32(0)
|
||||||
|
r := size
|
||||||
|
for l < r {
|
||||||
|
x := ((l + r) >> 1)
|
||||||
|
if ip < m.ip4[x] {
|
||||||
|
r = x
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
nip := normalize4(ip, m.prefix4[x])
|
||||||
|
if nip == m.ip4[x] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
l = x + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return l > 0 && normalize4(ip, m.prefix4[l-1]) == m.ip4[l-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func less6(a ipv6, b ipv6) bool {
|
||||||
|
return a.a < b.a || (a.a == b.a && a.b < b.b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *GeoIPMatcher) match6(ip ipv6) bool {
|
||||||
|
if len(m.ip6) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if less6(ip, m.ip6[0]) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
size := uint32(len(m.ip6))
|
||||||
|
l := uint32(0)
|
||||||
|
r := size
|
||||||
|
for l < r {
|
||||||
|
x := (l + r) / 2
|
||||||
|
if less6(ip, m.ip6[x]) {
|
||||||
|
r = x
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if normalize6(ip, m.prefix6[x]) == m.ip6[x] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
l = x + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return l > 0 && normalize6(ip, m.prefix6[l-1]) == m.ip6[l-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match returns true if the given ip is included by the GeoIP.
|
||||||
|
func (m *GeoIPMatcher) Match(ip net.IP) bool {
|
||||||
|
switch len(ip) {
|
||||||
|
case 4:
|
||||||
|
if m.reverseMatch {
|
||||||
|
return !m.match4(binary.BigEndian.Uint32(ip))
|
||||||
|
}
|
||||||
|
return m.match4(binary.BigEndian.Uint32(ip))
|
||||||
|
case 16:
|
||||||
|
if m.reverseMatch {
|
||||||
|
return !m.match6(ipv6{
|
||||||
|
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||||
|
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return m.match6(ipv6{
|
||||||
|
a: binary.BigEndian.Uint64(ip[0:8]),
|
||||||
|
b: binary.BigEndian.Uint64(ip[8:16]),
|
||||||
|
})
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GeoIPMatcherContainer is a container for GeoIPMatchers. It keeps unique copies of GeoIPMatcher by country code.
|
||||||
|
type GeoIPMatcherContainer struct {
|
||||||
|
matchers []*GeoIPMatcher
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a new GeoIP set into the container.
|
||||||
|
// If the country code of GeoIP is not empty, GeoIPMatcherContainer will try to find an existing one, instead of adding a new one.
|
||||||
|
func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) {
|
||||||
|
if len(geoip.CountryCode) > 0 {
|
||||||
|
for _, m := range c.matchers {
|
||||||
|
if m.countryCode == geoip.CountryCode && m.reverseMatch == geoip.ReverseMatch {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
m := &GeoIPMatcher{
|
||||||
|
countryCode: geoip.CountryCode,
|
||||||
|
reverseMatch: geoip.ReverseMatch,
|
||||||
|
}
|
||||||
|
if err := m.Init(geoip.Cidr); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(geoip.CountryCode) > 0 {
|
||||||
|
c.matchers = append(c.matchers, m)
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var globalGeoIPContainer GeoIPMatcherContainer
|
||||||
|
|
||||||
|
type MultiGeoIPMatcher struct {
|
||||||
|
matchers []*GeoIPMatcher
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGeoIPMatcher(geoip *GeoIP) (*GeoIPMatcher, error) {
|
||||||
|
matcher, err := globalGeoIPContainer.Add(geoip)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return matcher, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MultiGeoIPMatcher) ApplyIp(ip net.IP) bool {
|
||||||
|
|
||||||
|
for _, matcher := range m.matchers {
|
||||||
|
if matcher.Match(ip) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMultiGeoIPMatcher(geoips []*GeoIP) (*MultiGeoIPMatcher, error) {
|
||||||
|
var matchers []*GeoIPMatcher
|
||||||
|
for _, geoip := range geoips {
|
||||||
|
matcher, err := globalGeoIPContainer.Add(geoip)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
matchers = append(matchers, matcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
matcher := &MultiGeoIPMatcher{
|
||||||
|
matchers: matchers,
|
||||||
|
}
|
||||||
|
|
||||||
|
return matcher, nil
|
||||||
|
}
|
||||||
|
@ -26,7 +26,7 @@ func ReadFile(path string) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ReadAsset(file string) ([]byte, error) {
|
func ReadAsset(file string) ([]byte, error) {
|
||||||
return ReadFile(C.Path.Resolve(file))
|
return ReadFile(C.Path.GetAssetLocation(file))
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadIP(filename, country string) ([]*router.CIDR, error) {
|
func loadIP(filename, country string) ([]*router.CIDR, error) {
|
||||||
|
@ -2,10 +2,39 @@ package geodata
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var geoLoaderName = "memconservative"
|
||||||
|
|
||||||
|
// geoLoaderName = "standard"
|
||||||
|
|
||||||
|
func LoaderName() string {
|
||||||
|
return geoLoaderName
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetLoader(newLoader string) {
|
||||||
|
if newLoader == "memc" {
|
||||||
|
newLoader = "memconservative"
|
||||||
|
}
|
||||||
|
geoLoaderName = newLoader
|
||||||
|
}
|
||||||
|
|
||||||
|
func Verify(name string) bool {
|
||||||
|
switch name {
|
||||||
|
case C.GeositeName:
|
||||||
|
_, _, err := LoadGeoSiteMatcher("CN")
|
||||||
|
return err == nil
|
||||||
|
case C.GeoipName:
|
||||||
|
_, _, err := LoadGeoIPMatcher("CN")
|
||||||
|
return err == nil
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
||||||
geoLoaderName := "standard"
|
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
@ -28,3 +57,28 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
|
|
||||||
return matcher, len(domains), nil
|
return matcher, len(domains), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
||||||
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
records, err := geoLoader.LoadGeoIP(strings.ReplaceAll(country, "!", ""))
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
geoIP := &router.GeoIP{
|
||||||
|
CountryCode: country,
|
||||||
|
Cidr: records,
|
||||||
|
ReverseMatch: strings.Contains(country, "!"),
|
||||||
|
}
|
||||||
|
|
||||||
|
matcher, err := router.NewGeoIPMatcher(geoIP)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return matcher, len(records), nil
|
||||||
|
}
|
||||||
|
@ -1,12 +1,11 @@
|
|||||||
package mmdb
|
package mmdb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"github.com/oschwald/geoip2-golang"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -2,11 +2,11 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -24,8 +24,19 @@ func FindProcessName(network string, srcIP netip.Addr, srcPort int) (string, err
|
|||||||
return findProcessName(network, srcIP, srcPort)
|
return findProcessName(network, srcIP, srcPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func FindUid(network string, srcIP netip.Addr, srcPort int) (int32, error) {
|
||||||
|
_, uid, err := resolveSocketByNetlink(network, srcIP, srcPort)
|
||||||
|
if err != nil {
|
||||||
|
return -1, err
|
||||||
|
}
|
||||||
|
return uid, nil
|
||||||
|
}
|
||||||
|
|
||||||
func ShouldFindProcess(metadata *C.Metadata) bool {
|
func ShouldFindProcess(metadata *C.Metadata) bool {
|
||||||
if metadata.Process != "" {
|
if runtime.GOOS == "android" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if metadata.Process != "" || metadata.ProcessPath != "" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for _, ip := range localIPs {
|
for _, ip := range localIPs {
|
||||||
|
@ -17,6 +17,10 @@ const (
|
|||||||
proccallnumpidinfo = 0x2
|
proccallnumpidinfo = 0x2
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
|
return 0, 0, ErrPlatformNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, port int) (string, error) {
|
||||||
var spath string
|
var spath string
|
||||||
switch network {
|
switch network {
|
||||||
|
@ -21,6 +21,10 @@ var (
|
|||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
|
return 0, 0, ErrPlatformNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
if err := initSearcher(); err != nil {
|
if err := initSearcher(); err != nil {
|
||||||
|
@ -37,7 +37,6 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (string, error)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return resolveProcessNameByProcSearch(inode, uid)
|
return resolveProcessNameByProcSearch(inode, uid)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,7 +107,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32,
|
|||||||
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
||||||
}
|
}
|
||||||
|
|
||||||
inode, uid := unpackSocketDiagResponse(&messages[0])
|
inode, uid := unpackSocketDiagResponse(&message)
|
||||||
if inode < 0 || uid < 0 {
|
if inode < 0 || uid < 0 {
|
||||||
return 0, 0, fmt.Errorf("invalid inode(%d) or uid(%d)", inode, uid)
|
return 0, 0, fmt.Errorf("invalid inode(%d) or uid(%d)", inode, uid)
|
||||||
}
|
}
|
||||||
|
@ -7,3 +7,7 @@ import "net/netip"
|
|||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) {
|
||||||
return "", ErrPlatformNotSupport
|
return "", ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
|
return 0, 0, ErrPlatformNotSupport
|
||||||
|
}
|
||||||
|
@ -29,6 +29,10 @@ var (
|
|||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) {
|
||||||
|
return 0, 0, ErrPlatformNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
func initWin32API() error {
|
func initWin32API() error {
|
||||||
h, err := windows.LoadLibrary("iphlpapi.dll")
|
h, err := windows.LoadLibrary("iphlpapi.dll")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -215,8 +219,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
uintptr(h),
|
uintptr(h),
|
||||||
uintptr(1),
|
uintptr(1),
|
||||||
uintptr(unsafe.Pointer(&buf[0])),
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
uintptr(unsafe.Pointer(&size)),
|
uintptr(unsafe.Pointer(&size)))
|
||||||
)
|
|
||||||
if r1 == 0 {
|
if r1 == 0 {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
@ -40,6 +40,10 @@ type Resolver interface {
|
|||||||
ResolveIP(host string) (ip netip.Addr, err error)
|
ResolveIP(host string) (ip netip.Addr, err error)
|
||||||
ResolveIPv4(host string) (ip netip.Addr, err error)
|
ResolveIPv4(host string) (ip netip.Addr, err error)
|
||||||
ResolveIPv6(host string) (ip netip.Addr, err error)
|
ResolveIPv6(host string) (ip netip.Addr, err error)
|
||||||
|
ResolveAllIP(host string) (ip []netip.Addr, err error)
|
||||||
|
ResolveAllIPPrimaryIPv4(host string) (ips []netip.Addr, err error)
|
||||||
|
ResolveAllIPv4(host string) (ips []netip.Addr, err error)
|
||||||
|
ResolveAllIPv6(host string) (ips []netip.Addr, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv4 with a host, return ipv4
|
// ResolveIPv4 with a host, return ipv4
|
||||||
@ -48,43 +52,11 @@ func ResolveIPv4(host string) (netip.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ResolveIPv4WithResolver(host string, r Resolver) (netip.Addr, error) {
|
func ResolveIPv4WithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if ips, err := ResolveAllIPv4WithResolver(host, r); err == nil {
|
||||||
if ip := node.Data; ip.Is4() {
|
return ips[rand.Intn(len(ips))], nil
|
||||||
return ip, nil
|
} else {
|
||||||
}
|
return netip.Addr{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
|
||||||
if err == nil {
|
|
||||||
if ip.Is4() {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
return netip.Addr{}, ErrIPVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
if r != nil {
|
|
||||||
return r.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
|
||||||
if err != nil {
|
|
||||||
return netip.Addr{}, err
|
|
||||||
} else if len(ipAddrs) == 0 {
|
|
||||||
return netip.Addr{}, ErrIPNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
ip := ipAddrs[rand.Intn(len(ipAddrs))].To4()
|
|
||||||
if ip == nil {
|
|
||||||
return netip.Addr{}, ErrIPVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
return netip.AddrFrom4(*(*[4]byte)(ip)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return netip.Addr{}, ErrIPNotFound
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv6 with a host, return ipv6
|
// ResolveIPv6 with a host, return ipv6
|
||||||
@ -93,74 +65,20 @@ func ResolveIPv6(host string) (netip.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ResolveIPv6WithResolver(host string, r Resolver) (netip.Addr, error) {
|
func ResolveIPv6WithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||||
if DisableIPv6 {
|
if ips, err := ResolveAllIPv6WithResolver(host, r); err == nil {
|
||||||
return netip.Addr{}, ErrIPv6Disabled
|
return ips[rand.Intn(len(ips))], nil
|
||||||
|
} else {
|
||||||
|
return netip.Addr{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
|
||||||
if ip := node.Data; ip.Is6() {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
|
||||||
if err == nil {
|
|
||||||
if ip.Is6() {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
return netip.Addr{}, ErrIPVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
if r != nil {
|
|
||||||
return r.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip6", host)
|
|
||||||
if err != nil {
|
|
||||||
return netip.Addr{}, err
|
|
||||||
} else if len(ipAddrs) == 0 {
|
|
||||||
return netip.Addr{}, ErrIPNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))])), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return netip.Addr{}, ErrIPNotFound
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
||||||
func ResolveIPWithResolver(host string, r Resolver) (netip.Addr, error) {
|
func ResolveIPWithResolver(host string, r Resolver) (netip.Addr, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if ips, err := ResolveAllIPPrimaryIPv4WithResolver(host, r); err == nil {
|
||||||
return node.Data, nil
|
return ips[rand.Intn(len(ips))], nil
|
||||||
|
} else {
|
||||||
|
return netip.Addr{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if r != nil {
|
|
||||||
if DisableIPv6 {
|
|
||||||
return r.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
return r.ResolveIP(host)
|
|
||||||
} else if DisableIPv6 {
|
|
||||||
return ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
|
||||||
if err == nil {
|
|
||||||
return ip, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
|
||||||
if err != nil {
|
|
||||||
return netip.Addr{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nnip.IpToAddr(ipAddr.IP), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return netip.Addr{}, ErrIPNotFound
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIP with a host, return ip
|
// ResolveIP with a host, return ip
|
||||||
@ -191,3 +109,182 @@ func ResolveProxyServerHost(host string) (netip.Addr, error) {
|
|||||||
}
|
}
|
||||||
return ResolveIP(host)
|
return ResolveIP(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPv6WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||||
|
if DisableIPv6 {
|
||||||
|
return []netip.Addr{}, ErrIPv6Disabled
|
||||||
|
}
|
||||||
|
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
if ip := node.Data; ip.Is6() {
|
||||||
|
return []netip.Addr{ip}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err == nil {
|
||||||
|
if ip.Is6() {
|
||||||
|
return []netip.Addr{ip}, nil
|
||||||
|
}
|
||||||
|
return []netip.Addr{}, ErrIPVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
if r != nil {
|
||||||
|
return r.ResolveAllIPv6(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver == nil {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip6", host)
|
||||||
|
if err != nil {
|
||||||
|
return []netip.Addr{}, err
|
||||||
|
} else if len(ipAddrs) == 0 {
|
||||||
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{netip.AddrFrom16(*(*[16]byte)(ipAddrs[rand.Intn(len(ipAddrs))]))}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
if ip := node.Data; ip.Is4() {
|
||||||
|
return []netip.Addr{node.Data}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err == nil {
|
||||||
|
if ip.Is4() {
|
||||||
|
return []netip.Addr{ip}, nil
|
||||||
|
}
|
||||||
|
return []netip.Addr{}, ErrIPVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
if r != nil {
|
||||||
|
return r.ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver == nil {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
||||||
|
if err != nil {
|
||||||
|
return []netip.Addr{}, err
|
||||||
|
} else if len(ipAddrs) == 0 {
|
||||||
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := ipAddrs[rand.Intn(len(ipAddrs))].To4()
|
||||||
|
if ip == nil {
|
||||||
|
return []netip.Addr{}, ErrIPVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{netip.AddrFrom4(*(*[4]byte)(ip))}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPWithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
return []netip.Addr{node.Data}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if r != nil {
|
||||||
|
if DisableIPv6 {
|
||||||
|
return r.ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.ResolveAllIP(host)
|
||||||
|
} else if DisableIPv6 {
|
||||||
|
return ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err == nil {
|
||||||
|
return []netip.Addr{ip}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver == nil {
|
||||||
|
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||||
|
if err != nil {
|
||||||
|
return []netip.Addr{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPPrimaryIPv4WithResolver(host string, r Resolver) ([]netip.Addr, error) {
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
return []netip.Addr{node.Data}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if r != nil {
|
||||||
|
if DisableIPv6 {
|
||||||
|
return r.ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.ResolveAllIPPrimaryIPv4(host)
|
||||||
|
} else if DisableIPv6 {
|
||||||
|
return ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err == nil {
|
||||||
|
return []netip.Addr{ip}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver == nil {
|
||||||
|
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||||
|
if err != nil {
|
||||||
|
return []netip.Addr{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{nnip.IpToAddr(ipAddr.IP)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return []netip.Addr{}, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIP(host string) ([]netip.Addr, error) {
|
||||||
|
return ResolveAllIPWithResolver(host, DefaultResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPv4(host string) ([]netip.Addr, error) {
|
||||||
|
return ResolveAllIPv4WithResolver(host, DefaultResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPv6(host string) ([]netip.Addr, error) {
|
||||||
|
return ResolveAllIPv6WithResolver(host, DefaultResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPv6ProxyServerHost(host string) ([]netip.Addr, error) {
|
||||||
|
if ProxyServerHostResolver != nil {
|
||||||
|
return ResolveAllIPv6WithResolver(host, ProxyServerHostResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResolveAllIPv6(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPv4ProxyServerHost(host string) ([]netip.Addr, error) {
|
||||||
|
if ProxyServerHostResolver != nil {
|
||||||
|
return ResolveAllIPv4WithResolver(host, ProxyServerHostResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveAllIPProxyServerHost(host string) ([]netip.Addr, error) {
|
||||||
|
if ProxyServerHostResolver != nil {
|
||||||
|
return ResolveAllIPWithResolver(host, ProxyServerHostResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResolveAllIP(host)
|
||||||
|
}
|
||||||
|
167
component/sniffer/dispatcher.go
Normal file
167
component/sniffer/dispatcher.go
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
package sniffer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
|
||||||
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrorUnsupportedSniffer = errors.New("unsupported sniffer")
|
||||||
|
ErrorSniffFailed = errors.New("all sniffer failed")
|
||||||
|
)
|
||||||
|
|
||||||
|
var Dispatcher SnifferDispatcher
|
||||||
|
|
||||||
|
type (
|
||||||
|
SnifferDispatcher struct {
|
||||||
|
enable bool
|
||||||
|
|
||||||
|
sniffers []C.Sniffer
|
||||||
|
|
||||||
|
foreDomain *trie.DomainTrie[bool]
|
||||||
|
skipSNI *trie.DomainTrie[bool]
|
||||||
|
portRanges *[]utils.Range[uint16]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
||||||
|
bufConn, ok := conn.(*CN.BufferedConn)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if metadata.Host == "" || sd.foreDomain.Search(metadata.Host) != nil {
|
||||||
|
port, err := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
if err != nil {
|
||||||
|
log.Debugln("[Sniffer] Dst port is error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
inWhitelist := false
|
||||||
|
for _, portRange := range *sd.portRanges {
|
||||||
|
if portRange.Contains(uint16(port)) {
|
||||||
|
inWhitelist = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !inWhitelist {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if host, err := sd.sniffDomain(bufConn, metadata); err != nil {
|
||||||
|
log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%s] to [%s:%s]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
if sd.skipSNI.Search(host) != nil {
|
||||||
|
log.Debugln("[Sniffer] Skip sni[%s]", host)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sd.replaceDomain(metadata, host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string) {
|
||||||
|
log.Debugln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
||||||
|
metadata.SrcIP, metadata.SrcPort,
|
||||||
|
metadata.DstIP, metadata.DstPort,
|
||||||
|
metadata.Host, host)
|
||||||
|
|
||||||
|
metadata.AddrType = C.AtypDomainName
|
||||||
|
metadata.Host = host
|
||||||
|
metadata.DNSMode = C.DNSMapping
|
||||||
|
resolver.InsertHostByIP(metadata.DstIP, host)
|
||||||
|
metadata.DstIP = netip.Addr{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sd *SnifferDispatcher) Enable() bool {
|
||||||
|
return sd.enable
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sd *SnifferDispatcher) sniffDomain(conn *CN.BufferedConn, metadata *C.Metadata) (string, error) {
|
||||||
|
for _, sniffer := range sd.sniffers {
|
||||||
|
if sniffer.SupportNetwork() == C.TCP {
|
||||||
|
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||||
|
_, err := conn.Peek(1)
|
||||||
|
conn.SetReadDeadline(time.Time{})
|
||||||
|
if err != nil {
|
||||||
|
_, ok := err.(*net.OpError)
|
||||||
|
if ok {
|
||||||
|
log.Errorln("[Sniffer] [%s] Maybe read timeout, Consider adding skip", metadata.DstIP.String())
|
||||||
|
conn.Close()
|
||||||
|
}
|
||||||
|
log.Errorln("[Sniffer] %v", err)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
bufferedLen := conn.Buffered()
|
||||||
|
bytes, err := conn.Peek(bufferedLen)
|
||||||
|
if err != nil {
|
||||||
|
log.Debugln("[Sniffer] the data length not enough")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
host, err := sniffer.SniffTCP(bytes)
|
||||||
|
if err != nil {
|
||||||
|
log.Debugln("[Sniffer] [%s] Sniff data failed %s", sniffer.Protocol(), metadata.DstIP)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", ErrorSniffFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
||||||
|
dispatcher := SnifferDispatcher{
|
||||||
|
enable: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
return &dispatcher, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSnifferDispatcher(needSniffer []C.SnifferType, forceDomain *trie.DomainTrie[bool],
|
||||||
|
skipSNI *trie.DomainTrie[bool], ports *[]utils.Range[uint16]) (*SnifferDispatcher, error) {
|
||||||
|
dispatcher := SnifferDispatcher{
|
||||||
|
enable: true,
|
||||||
|
foreDomain: forceDomain,
|
||||||
|
skipSNI: skipSNI,
|
||||||
|
portRanges: ports,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, snifferName := range needSniffer {
|
||||||
|
sniffer, err := NewSniffer(snifferName)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln("Sniffer name[%s] is error", snifferName)
|
||||||
|
return &SnifferDispatcher{enable: false}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatcher.sniffers = append(dispatcher.sniffers, sniffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &dispatcher, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSniffer(name C.SnifferType) (C.Sniffer, error) {
|
||||||
|
switch name {
|
||||||
|
case C.TLS:
|
||||||
|
return &TLSSniffer{}, nil
|
||||||
|
default:
|
||||||
|
return nil, ErrorUnsupportedSniffer
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package tls
|
package sniffer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
@ -142,7 +142,7 @@ func TestTLSHeaders(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range cases {
|
for _, test := range cases {
|
||||||
header, err := SniffTLS(test.input)
|
domain, err := SniffTLS(test.input)
|
||||||
if test.err {
|
if test.err {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("Exepct error but nil in test %v", test)
|
t.Errorf("Exepct error but nil in test %v", test)
|
||||||
@ -151,8 +151,8 @@ func TestTLSHeaders(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
|
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
|
||||||
}
|
}
|
||||||
if header.Domain() != test.domain {
|
if *domain != test.domain {
|
||||||
t.Error("expect domain ", test.domain, " but got ", header.Domain())
|
t.Error("expect domain ", test.domain, " but got ", domain)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,107 +1,116 @@
|
|||||||
package tls
|
package sniffer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrNoClue = errors.New("not enough information for making a decision")
|
|
||||||
|
|
||||||
type SniffHeader struct {
|
|
||||||
domain string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SniffHeader) Protocol() string {
|
|
||||||
return "tls"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SniffHeader) Domain() string {
|
|
||||||
return h.domain
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errNotTLS = errors.New("not TLS header")
|
errNotTLS = errors.New("not TLS header")
|
||||||
errNotClientHello = errors.New("not client hello")
|
errNotClientHello = errors.New("not client hello")
|
||||||
|
ErrNoClue = errors.New("not enough information for making a decision")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type TLSSniffer struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tls *TLSSniffer) Protocol() string {
|
||||||
|
return "tls"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tls *TLSSniffer) SupportNetwork() C.NetWork {
|
||||||
|
return C.TCP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tls *TLSSniffer) SniffTCP(bytes []byte) (string, error) {
|
||||||
|
domain, err := SniffTLS(bytes)
|
||||||
|
if err == nil {
|
||||||
|
return *domain, nil
|
||||||
|
} else {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func IsValidTLSVersion(major, minor byte) bool {
|
func IsValidTLSVersion(major, minor byte) bool {
|
||||||
return major == 3
|
return major == 3
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadClientHello returns server name (if any) from TLS client hello message.
|
// ReadClientHello returns server name (if any) from TLS client hello message.
|
||||||
// https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300
|
// https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300
|
||||||
func ReadClientHello(data []byte, h *SniffHeader) error {
|
func ReadClientHello(data []byte) (*string, error) {
|
||||||
if len(data) < 42 {
|
if len(data) < 42 {
|
||||||
return ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
sessionIDLen := int(data[38])
|
sessionIDLen := int(data[38])
|
||||||
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
|
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
|
||||||
return ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
data = data[39+sessionIDLen:]
|
data = data[39+sessionIDLen:]
|
||||||
if len(data) < 2 {
|
if len(data) < 2 {
|
||||||
return ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
|
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
|
||||||
// they are uint16s, the number must be even.
|
// they are uint16s, the number must be even.
|
||||||
cipherSuiteLen := int(data[0])<<8 | int(data[1])
|
cipherSuiteLen := int(data[0])<<8 | int(data[1])
|
||||||
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
|
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
data = data[2+cipherSuiteLen:]
|
data = data[2+cipherSuiteLen:]
|
||||||
if len(data) < 1 {
|
if len(data) < 1 {
|
||||||
return ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
compressionMethodsLen := int(data[0])
|
compressionMethodsLen := int(data[0])
|
||||||
if len(data) < 1+compressionMethodsLen {
|
if len(data) < 1+compressionMethodsLen {
|
||||||
return ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
data = data[1+compressionMethodsLen:]
|
data = data[1+compressionMethodsLen:]
|
||||||
|
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
if len(data) < 2 {
|
if len(data) < 2 {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
|
|
||||||
extensionsLength := int(data[0])<<8 | int(data[1])
|
extensionsLength := int(data[0])<<8 | int(data[1])
|
||||||
data = data[2:]
|
data = data[2:]
|
||||||
if extensionsLength != len(data) {
|
if extensionsLength != len(data) {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
|
|
||||||
for len(data) != 0 {
|
for len(data) != 0 {
|
||||||
if len(data) < 4 {
|
if len(data) < 4 {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
extension := uint16(data[0])<<8 | uint16(data[1])
|
extension := uint16(data[0])<<8 | uint16(data[1])
|
||||||
length := int(data[2])<<8 | int(data[3])
|
length := int(data[2])<<8 | int(data[3])
|
||||||
data = data[4:]
|
data = data[4:]
|
||||||
if len(data) < length {
|
if len(data) < length {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
|
|
||||||
if extension == 0x00 { /* extensionServerName */
|
if extension == 0x00 { /* extensionServerName */
|
||||||
d := data[:length]
|
d := data[:length]
|
||||||
if len(d) < 2 {
|
if len(d) < 2 {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
namesLen := int(d[0])<<8 | int(d[1])
|
namesLen := int(d[0])<<8 | int(d[1])
|
||||||
d = d[2:]
|
d = d[2:]
|
||||||
if len(d) != namesLen {
|
if len(d) != namesLen {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
for len(d) > 0 {
|
for len(d) > 0 {
|
||||||
if len(d) < 3 {
|
if len(d) < 3 {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
nameType := d[0]
|
nameType := d[0]
|
||||||
nameLen := int(d[1])<<8 | int(d[2])
|
nameLen := int(d[1])<<8 | int(d[2])
|
||||||
d = d[3:]
|
d = d[3:]
|
||||||
if len(d) < nameLen {
|
if len(d) < nameLen {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
if nameType == 0 {
|
if nameType == 0 {
|
||||||
serverName := string(d[:nameLen])
|
serverName := string(d[:nameLen])
|
||||||
@ -109,21 +118,22 @@ func ReadClientHello(data []byte, h *SniffHeader) error {
|
|||||||
// trailing dot. See
|
// trailing dot. See
|
||||||
// https://tools.ietf.org/html/rfc6066#section-3.
|
// https://tools.ietf.org/html/rfc6066#section-3.
|
||||||
if strings.HasSuffix(serverName, ".") {
|
if strings.HasSuffix(serverName, ".") {
|
||||||
return errNotClientHello
|
return nil, errNotClientHello
|
||||||
}
|
}
|
||||||
h.domain = serverName
|
|
||||||
return nil
|
return &serverName, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
d = d[nameLen:]
|
d = d[nameLen:]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
data = data[length:]
|
data = data[length:]
|
||||||
}
|
}
|
||||||
|
|
||||||
return errNotTLS
|
return nil, errNotTLS
|
||||||
}
|
}
|
||||||
|
|
||||||
func SniffTLS(b []byte) (*SniffHeader, error) {
|
func SniffTLS(b []byte) (*string, error) {
|
||||||
if len(b) < 5 {
|
if len(b) < 5 {
|
||||||
return nil, ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
@ -139,10 +149,9 @@ func SniffTLS(b []byte) (*SniffHeader, error) {
|
|||||||
return nil, ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
|
|
||||||
h := &SniffHeader{}
|
domain, err := ReadClientHello(b[5 : 5+headerLen])
|
||||||
err := ReadClientHello(b[5:5+headerLen], h)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return h, nil
|
return domain, nil
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
44
component/trie/ipcidr_node.go
Normal file
44
component/trie/ipcidr_node.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package trie
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrorOverMaxValue = errors.New("the value don't over max value")
|
||||||
|
)
|
||||||
|
|
||||||
|
type IpCidrNode struct {
|
||||||
|
Mark bool
|
||||||
|
child map[uint32]*IpCidrNode
|
||||||
|
maxValue uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewIpCidrNode(mark bool, maxValue uint32) *IpCidrNode {
|
||||||
|
ipCidrNode := &IpCidrNode{
|
||||||
|
Mark: mark,
|
||||||
|
child: map[uint32]*IpCidrNode{},
|
||||||
|
maxValue: maxValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
return ipCidrNode
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *IpCidrNode) addChild(value uint32) error {
|
||||||
|
if value > n.maxValue {
|
||||||
|
return ErrorOverMaxValue
|
||||||
|
}
|
||||||
|
|
||||||
|
n.child[value] = NewIpCidrNode(false, n.maxValue)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *IpCidrNode) hasChild(value uint32) bool {
|
||||||
|
return n.getChild(value) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *IpCidrNode) getChild(value uint32) *IpCidrNode {
|
||||||
|
if value <= n.maxValue {
|
||||||
|
return n.child[value]
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
255
component/trie/ipcidr_trie.go
Normal file
255
component/trie/ipcidr_trie.go
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
package trie
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type IPV6 bool
|
||||||
|
|
||||||
|
const (
|
||||||
|
ipv4GroupMaxValue = 0xFF
|
||||||
|
ipv6GroupMaxValue = 0xFFFF
|
||||||
|
)
|
||||||
|
|
||||||
|
type IpCidrTrie struct {
|
||||||
|
ipv4Trie *IpCidrNode
|
||||||
|
ipv6Trie *IpCidrNode
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewIpCidrTrie() *IpCidrTrie {
|
||||||
|
return &IpCidrTrie{
|
||||||
|
ipv4Trie: NewIpCidrNode(false, ipv4GroupMaxValue),
|
||||||
|
ipv6Trie: NewIpCidrNode(false, ipv6GroupMaxValue),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (trie *IpCidrTrie) AddIpCidr(ipCidr *net.IPNet) error {
|
||||||
|
subIpCidr, subCidr, isIpv4, err := ipCidrToSubIpCidr(ipCidr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, sub := range subIpCidr {
|
||||||
|
addIpCidr(trie, isIpv4, sub, subCidr/8)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (trie *IpCidrTrie) AddIpCidrForString(ipCidr string) error {
|
||||||
|
_, ipNet, err := net.ParseCIDR(ipCidr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return trie.AddIpCidr(ipNet)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (trie *IpCidrTrie) IsContain(ip net.IP) bool {
|
||||||
|
ip, isIpv4 := checkAndConverterIp(ip)
|
||||||
|
if ip == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var groupValues []uint32
|
||||||
|
var ipCidrNode *IpCidrNode
|
||||||
|
|
||||||
|
if isIpv4 {
|
||||||
|
ipCidrNode = trie.ipv4Trie
|
||||||
|
for _, group := range ip {
|
||||||
|
groupValues = append(groupValues, uint32(group))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ipCidrNode = trie.ipv6Trie
|
||||||
|
for i := 0; i < len(ip); i += 2 {
|
||||||
|
groupValues = append(groupValues, getIpv6GroupValue(ip[i], ip[i+1]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return search(ipCidrNode, groupValues) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (trie *IpCidrTrie) IsContainForString(ipString string) bool {
|
||||||
|
return trie.IsContain(net.ParseIP(ipString))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ipCidrToSubIpCidr(ipNet *net.IPNet) ([]net.IP, int, bool, error) {
|
||||||
|
maskSize, _ := ipNet.Mask.Size()
|
||||||
|
var (
|
||||||
|
ipList []net.IP
|
||||||
|
newMaskSize int
|
||||||
|
isIpv4 bool
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
|
||||||
|
ip, isIpv4 := checkAndConverterIp(ipNet.IP)
|
||||||
|
ipList, newMaskSize, err = subIpCidr(ip, maskSize, isIpv4)
|
||||||
|
|
||||||
|
return ipList, newMaskSize, isIpv4, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func subIpCidr(ip net.IP, maskSize int, isIpv4 bool) ([]net.IP, int, error) {
|
||||||
|
var subIpCidrList []net.IP
|
||||||
|
groupSize := 8
|
||||||
|
if !isIpv4 {
|
||||||
|
groupSize = 16
|
||||||
|
}
|
||||||
|
|
||||||
|
if maskSize%groupSize == 0 {
|
||||||
|
return append(subIpCidrList, ip), maskSize, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
lastByteMaskSize := maskSize % 8
|
||||||
|
lastByteMaskIndex := maskSize / 8
|
||||||
|
subIpCidrNum := 0xFF >> lastByteMaskSize
|
||||||
|
for i := 0; i <= subIpCidrNum; i++ {
|
||||||
|
subIpCidr := make([]byte, len(ip))
|
||||||
|
copy(subIpCidr, ip)
|
||||||
|
subIpCidr[lastByteMaskIndex] += byte(i)
|
||||||
|
subIpCidrList = append(subIpCidrList, subIpCidr)
|
||||||
|
}
|
||||||
|
|
||||||
|
newMaskSize := (lastByteMaskIndex + 1) * 8
|
||||||
|
if !isIpv4 {
|
||||||
|
newMaskSize = (lastByteMaskIndex/2 + 1) * 16
|
||||||
|
}
|
||||||
|
|
||||||
|
return subIpCidrList, newMaskSize, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addIpCidr(trie *IpCidrTrie, isIpv4 bool, ip net.IP, groupSize int) {
|
||||||
|
if isIpv4 {
|
||||||
|
addIpv4Cidr(trie, ip, groupSize)
|
||||||
|
} else {
|
||||||
|
addIpv6Cidr(trie, ip, groupSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func addIpv4Cidr(trie *IpCidrTrie, ip net.IP, groupSize int) {
|
||||||
|
preNode := trie.ipv4Trie
|
||||||
|
node := preNode.getChild(uint32(ip[0]))
|
||||||
|
if node == nil {
|
||||||
|
err := preNode.addChild(uint32(ip[0]))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
node = preNode.getChild(uint32(ip[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 1; i < groupSize; i++ {
|
||||||
|
if node.Mark {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
groupValue := uint32(ip[i])
|
||||||
|
if !node.hasChild(groupValue) {
|
||||||
|
err := node.addChild(groupValue)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln(err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
preNode = node
|
||||||
|
node = node.getChild(groupValue)
|
||||||
|
if node == nil {
|
||||||
|
err := preNode.addChild(uint32(ip[i-1]))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
node = preNode.getChild(uint32(ip[i-1]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
node.Mark = true
|
||||||
|
cleanChild(node)
|
||||||
|
}
|
||||||
|
|
||||||
|
func addIpv6Cidr(trie *IpCidrTrie, ip net.IP, groupSize int) {
|
||||||
|
preNode := trie.ipv6Trie
|
||||||
|
node := preNode.getChild(getIpv6GroupValue(ip[0], ip[1]))
|
||||||
|
if node == nil {
|
||||||
|
err := preNode.addChild(getIpv6GroupValue(ip[0], ip[1]))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
node = preNode.getChild(getIpv6GroupValue(ip[0], ip[1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 2; i < groupSize; i += 2 {
|
||||||
|
if node.Mark {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
groupValue := getIpv6GroupValue(ip[i], ip[i+1])
|
||||||
|
if !node.hasChild(groupValue) {
|
||||||
|
err := node.addChild(groupValue)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln(err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
preNode = node
|
||||||
|
node = node.getChild(groupValue)
|
||||||
|
if node == nil {
|
||||||
|
err := preNode.addChild(getIpv6GroupValue(ip[i-2], ip[i-1]))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
node = preNode.getChild(getIpv6GroupValue(ip[i-2], ip[i-1]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
node.Mark = true
|
||||||
|
cleanChild(node)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getIpv6GroupValue(high, low byte) uint32 {
|
||||||
|
return (uint32(high) << 8) | uint32(low)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanChild(node *IpCidrNode) {
|
||||||
|
for i := uint32(0); i < uint32(len(node.child)); i++ {
|
||||||
|
delete(node.child, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func search(root *IpCidrNode, groupValues []uint32) *IpCidrNode {
|
||||||
|
node := root.getChild(groupValues[0])
|
||||||
|
if node == nil || node.Mark {
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range groupValues[1:] {
|
||||||
|
if !node.hasChild(value) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
node = node.getChild(value)
|
||||||
|
|
||||||
|
if node == nil || node.Mark {
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// return net.IP To4 or To16 and is ipv4
|
||||||
|
func checkAndConverterIp(ip net.IP) (net.IP, bool) {
|
||||||
|
ipResult := ip.To4()
|
||||||
|
if ipResult == nil {
|
||||||
|
ipResult = ip.To16()
|
||||||
|
if ipResult == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return ipResult, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return ipResult, true
|
||||||
|
}
|
100
component/trie/trie_test.go
Normal file
100
component/trie/trie_test.go
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
package trie
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
import "github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
func TestIpv4AddSuccess(t *testing.T) {
|
||||||
|
trie := NewIpCidrTrie()
|
||||||
|
err := trie.AddIpCidrForString("10.0.0.2/16")
|
||||||
|
assert.Equal(t, nil, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIpv4AddFail(t *testing.T) {
|
||||||
|
trie := NewIpCidrTrie()
|
||||||
|
err := trie.AddIpCidrForString("333.00.23.2/23")
|
||||||
|
assert.IsType(t, new(net.ParseError), err)
|
||||||
|
|
||||||
|
err = trie.AddIpCidrForString("22.3.34.2/222")
|
||||||
|
assert.IsType(t, new(net.ParseError), err)
|
||||||
|
|
||||||
|
err = trie.AddIpCidrForString("2.2.2.2")
|
||||||
|
assert.IsType(t, new(net.ParseError), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIpv4Search(t *testing.T) {
|
||||||
|
trie := NewIpCidrTrie()
|
||||||
|
// Boundary testing
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("149.154.160.0/20"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("149.154.160.0"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("149.154.175.255"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("149.154.176.0"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("149.154.159.255"))
|
||||||
|
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("129.2.36.0/16"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("10.2.36.0/18"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("16.2.23.0/24"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("11.2.13.2/26"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("55.5.6.3/8"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("66.23.25.4/6"))
|
||||||
|
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("129.2.3.65"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("15.2.3.1"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("11.2.13.1"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("55.0.0.0"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("64.0.0.0"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("128.0.0.0"))
|
||||||
|
|
||||||
|
assert.Equal(t, false, trie.IsContain(net.ParseIP("22")))
|
||||||
|
assert.Equal(t, false, trie.IsContain(net.ParseIP("")))
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIpv6AddSuccess(t *testing.T) {
|
||||||
|
trie := NewIpCidrTrie()
|
||||||
|
err := trie.AddIpCidrForString("2001:0db8:02de:0000:0000:0000:0000:0e13/32")
|
||||||
|
assert.Equal(t, nil, err)
|
||||||
|
|
||||||
|
err = trie.AddIpCidrForString("2001:1db8:f2de::0e13/18")
|
||||||
|
assert.Equal(t, nil, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIpv6AddFail(t *testing.T) {
|
||||||
|
trie := NewIpCidrTrie()
|
||||||
|
err := trie.AddIpCidrForString("2001::25de::cade/23")
|
||||||
|
assert.IsType(t, new(net.ParseError), err)
|
||||||
|
|
||||||
|
err = trie.AddIpCidrForString("2001:0fa3:25de::cade/222")
|
||||||
|
assert.IsType(t, new(net.ParseError), err)
|
||||||
|
|
||||||
|
err = trie.AddIpCidrForString("2001:0fa3:25de::cade")
|
||||||
|
assert.IsType(t, new(net.ParseError), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIpv6Search(t *testing.T) {
|
||||||
|
trie := NewIpCidrTrie()
|
||||||
|
|
||||||
|
// Boundary testing
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2a0a:f280::/32"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("2a0a:f280:0000:0000:0000:0000:0000:0000"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("2a0a:f280:ffff:ffff:ffff:ffff:ffff:ffff"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("2a0a:f279:ffff:ffff:ffff:ffff:ffff:ffff"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("2a0a:f281:0000:0000:0000:0000:0000:0000"))
|
||||||
|
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2001:b28:f23d:f001::e/128"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2001:67c:4e8:f002::e/12"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2001:b28:f23d:f003::e/96"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2001:67c:4e8:f002::a/32"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2001:67c:4e8:f004::a/60"))
|
||||||
|
assert.NoError(t, trie.AddIpCidrForString("2001:b28:f23f:f005::a/64"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("2001:b28:f23d:f001::e"))
|
||||||
|
assert.Equal(t, false, trie.IsContainForString("2222::fff2"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("2000::ffa0"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("2001:b28:f23f:f005:5662::"))
|
||||||
|
assert.Equal(t, true, trie.IsContainForString("2001:67c:4e8:9666::1213"))
|
||||||
|
|
||||||
|
assert.Equal(t, false, trie.IsContain(net.ParseIP("22233:22")))
|
||||||
|
|
||||||
|
}
|
522
config/config.go
522
config/config.go
@ -1,14 +1,22 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"container/list"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/listener/tun/ipstack/commons"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
R "github.com/Dreamacro/clash/rule"
|
||||||
|
RP "github.com/Dreamacro/clash/rule/provider"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
@ -23,26 +31,25 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/dns"
|
||||||
"github.com/Dreamacro/clash/listener/tun/ipstack/commons"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
rewrites "github.com/Dreamacro/clash/rewrite"
|
|
||||||
R "github.com/Dreamacro/clash/rule"
|
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// General config
|
// General config
|
||||||
type General struct {
|
type General struct {
|
||||||
Inbound
|
Inbound
|
||||||
Controller
|
Controller
|
||||||
Mode T.TunnelMode `json:"mode"`
|
Mode T.TunnelMode `json:"mode"`
|
||||||
LogLevel log.LogLevel `json:"log-level"`
|
UnifiedDelay bool
|
||||||
IPv6 bool `json:"ipv6"`
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
Sniffing bool `json:"sniffing"`
|
IPv6 bool `json:"ipv6"`
|
||||||
Interface string `json:"-"`
|
Interface string `json:"-"`
|
||||||
RoutingMark int `json:"-"`
|
RoutingMark int `json:"-"`
|
||||||
Tun Tun `json:"tun"`
|
GeodataMode bool `json:"geodata-mode"`
|
||||||
|
GeodataLoader string `json:"geodata-loader"`
|
||||||
|
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inbound config
|
// Inbound config
|
||||||
@ -52,7 +59,6 @@ type Inbound struct {
|
|||||||
RedirPort int `json:"redir-port"`
|
RedirPort int `json:"redir-port"`
|
||||||
TProxyPort int `json:"tproxy-port"`
|
TProxyPort int `json:"tproxy-port"`
|
||||||
MixedPort int `json:"mixed-port"`
|
MixedPort int `json:"mixed-port"`
|
||||||
MitmPort int `json:"mitm-port"`
|
|
||||||
Authentication []string `json:"authentication"`
|
Authentication []string `json:"authentication"`
|
||||||
AllowLan bool `json:"allow-lan"`
|
AllowLan bool `json:"allow-lan"`
|
||||||
BindAddress string `json:"bind-address"`
|
BindAddress string `json:"bind-address"`
|
||||||
@ -90,6 +96,12 @@ type FallbackFilter struct {
|
|||||||
GeoSite []*router.DomainMatcher `yaml:"geosite"`
|
GeoSite []*router.DomainMatcher `yaml:"geosite"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
GroupsList = list.New()
|
||||||
|
ProxiesList = list.New()
|
||||||
|
ParsingProxiesCallback func(groupsList *list.List, proxiesList *list.List)
|
||||||
|
)
|
||||||
|
|
||||||
// Profile config
|
// Profile config
|
||||||
type Profile struct {
|
type Profile struct {
|
||||||
StoreSelected bool `yaml:"store-selected"`
|
StoreSelected bool `yaml:"store-selected"`
|
||||||
@ -98,24 +110,29 @@ type Profile struct {
|
|||||||
|
|
||||||
// Tun config
|
// Tun config
|
||||||
type Tun struct {
|
type Tun struct {
|
||||||
Enable bool `yaml:"enable" json:"enable"`
|
Enable bool `yaml:"enable" json:"enable"`
|
||||||
Device string `yaml:"device" json:"device"`
|
Device string `yaml:"device" json:"device"`
|
||||||
Stack C.TUNStack `yaml:"stack" json:"stack"`
|
Stack C.TUNStack `yaml:"stack" json:"stack"`
|
||||||
DNSHijack []C.DNSUrl `yaml:"dns-hijack" json:"dns-hijack"`
|
DNSHijack []netip.AddrPort `yaml:"dns-hijack" json:"dns-hijack"`
|
||||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||||
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
|
AutoDetectInterface bool `yaml:"auto-detect-interface" json:"auto-detect-interface"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// IPTables config
|
// IPTables config
|
||||||
type IPTables struct {
|
type IPTables struct {
|
||||||
Enable bool `yaml:"enable" json:"enable"`
|
Enable bool `yaml:"enable" json:"enable"`
|
||||||
InboundInterface string `yaml:"inbound-interface" json:"inbound-interface"`
|
InboundInterface string `yaml:"inbound-interface" json:"inbound-interface"`
|
||||||
|
Bypass []string `yaml:"bypass" json:"bypass"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mitm config
|
type Sniffer struct {
|
||||||
type Mitm struct {
|
Enable bool
|
||||||
Hosts *trie.DomainTrie[bool] `yaml:"hosts" json:"hosts"`
|
Force bool
|
||||||
Rules C.RewriteRule `yaml:"rules" json:"rules"`
|
Sniffers []C.SnifferType
|
||||||
|
Reverses *trie.DomainTrie[bool]
|
||||||
|
ForceDomain *trie.DomainTrie[bool]
|
||||||
|
SkipSNI *trie.DomainTrie[bool]
|
||||||
|
Ports *[]utils.Range[uint16]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Experimental config
|
// Experimental config
|
||||||
@ -123,17 +140,19 @@ type Experimental struct{}
|
|||||||
|
|
||||||
// Config is clash config manager
|
// Config is clash config manager
|
||||||
type Config struct {
|
type Config struct {
|
||||||
General *General
|
General *General
|
||||||
IPTables *IPTables
|
Tun *Tun
|
||||||
Mitm *Mitm
|
IPTables *IPTables
|
||||||
DNS *DNS
|
DNS *DNS
|
||||||
Experimental *Experimental
|
Experimental *Experimental
|
||||||
Hosts *trie.DomainTrie[netip.Addr]
|
Hosts *trie.DomainTrie[netip.Addr]
|
||||||
Profile *Profile
|
Profile *Profile
|
||||||
Rules []C.Rule
|
Rules []C.Rule
|
||||||
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
|
||||||
|
RuleProviders map[string]providerTypes.RuleProvider
|
||||||
|
Sniffer *Sniffer
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawDNS struct {
|
type RawDNS struct {
|
||||||
@ -160,9 +179,13 @@ type RawFallbackFilter struct {
|
|||||||
GeoSite []string `yaml:"geosite"`
|
GeoSite []string `yaml:"geosite"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawMitm struct {
|
type RawTun struct {
|
||||||
Hosts []string `yaml:"hosts" json:"hosts"`
|
Enable bool `yaml:"enable" json:"enable"`
|
||||||
Rules []string `yaml:"rules" json:"rules"`
|
Device string `yaml:"device" json:"device"`
|
||||||
|
Stack C.TUNStack `yaml:"stack" json:"stack"`
|
||||||
|
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
||||||
|
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
||||||
|
AutoDetectInterface bool `yaml:"auto-detect-interface"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawConfig struct {
|
type RawConfig struct {
|
||||||
@ -171,11 +194,11 @@ type RawConfig struct {
|
|||||||
RedirPort int `yaml:"redir-port"`
|
RedirPort int `yaml:"redir-port"`
|
||||||
TProxyPort int `yaml:"tproxy-port"`
|
TProxyPort int `yaml:"tproxy-port"`
|
||||||
MixedPort int `yaml:"mixed-port"`
|
MixedPort int `yaml:"mixed-port"`
|
||||||
MitmPort int `yaml:"mitm-port"`
|
|
||||||
Authentication []string `yaml:"authentication"`
|
Authentication []string `yaml:"authentication"`
|
||||||
AllowLan bool `yaml:"allow-lan"`
|
AllowLan bool `yaml:"allow-lan"`
|
||||||
BindAddress string `yaml:"bind-address"`
|
BindAddress string `yaml:"bind-address"`
|
||||||
Mode T.TunnelMode `yaml:"mode"`
|
Mode T.TunnelMode `yaml:"mode"`
|
||||||
|
UnifiedDelay bool `yaml:"unified-delay"`
|
||||||
LogLevel log.LogLevel `yaml:"log-level"`
|
LogLevel log.LogLevel `yaml:"log-level"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
ExternalController string `yaml:"external-controller"`
|
ExternalController string `yaml:"external-controller"`
|
||||||
@ -183,15 +206,17 @@ type RawConfig struct {
|
|||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
Interface string `yaml:"interface-name"`
|
Interface string `yaml:"interface-name"`
|
||||||
RoutingMark int `yaml:"routing-mark"`
|
RoutingMark int `yaml:"routing-mark"`
|
||||||
Sniffing bool `yaml:"sniffing"`
|
GeodataMode bool `yaml:"geodata-mode"`
|
||||||
ForceCertVerify bool `yaml:"force-cert-verify"`
|
GeodataLoader string `yaml:"geodata-loader"`
|
||||||
|
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||||
|
|
||||||
|
Sniffer SnifferRaw `yaml:"sniffer"`
|
||||||
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
||||||
|
RuleProvider map[string]map[string]any `yaml:"rule-providers"`
|
||||||
Hosts map[string]string `yaml:"hosts"`
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
DNS RawDNS `yaml:"dns"`
|
DNS RawDNS `yaml:"dns"`
|
||||||
Tun Tun `yaml:"tun"`
|
Tun RawTun `yaml:"tun"`
|
||||||
IPTables IPTables `yaml:"iptables"`
|
IPTables IPTables `yaml:"iptables"`
|
||||||
MITM RawMitm `yaml:"mitm"`
|
|
||||||
Experimental Experimental `yaml:"experimental"`
|
Experimental Experimental `yaml:"experimental"`
|
||||||
Profile Profile `yaml:"profile"`
|
Profile Profile `yaml:"profile"`
|
||||||
Proxy []map[string]any `yaml:"proxies"`
|
Proxy []map[string]any `yaml:"proxies"`
|
||||||
@ -199,6 +224,16 @@ type RawConfig struct {
|
|||||||
Rule []string `yaml:"rules"`
|
Rule []string `yaml:"rules"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SnifferRaw struct {
|
||||||
|
Enable bool `yaml:"enable" json:"enable"`
|
||||||
|
Sniffing []string `yaml:"sniffing" json:"sniffing"`
|
||||||
|
Force bool `yaml:"force" json:"force"`
|
||||||
|
Reverse []string `yaml:"reverses" json:"reverses"`
|
||||||
|
ForceDomain []string `yaml:"force-domain" json:"force-domain"`
|
||||||
|
SkipSNI []string `yaml:"skip-sni" json:"skip-sni"`
|
||||||
|
Ports []string `yaml:"port-whitelist" json:"port-whitelist"`
|
||||||
|
}
|
||||||
|
|
||||||
// Parse config
|
// Parse config
|
||||||
func Parse(buf []byte) (*Config, error) {
|
func Parse(buf []byte) (*Config, error) {
|
||||||
rawCfg, err := UnmarshalRawConfig(buf)
|
rawCfg, err := UnmarshalRawConfig(buf)
|
||||||
@ -212,41 +247,31 @@ func Parse(buf []byte) (*Config, error) {
|
|||||||
func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||||
// config with default value
|
// config with default value
|
||||||
rawCfg := &RawConfig{
|
rawCfg := &RawConfig{
|
||||||
AllowLan: false,
|
AllowLan: false,
|
||||||
Sniffing: false,
|
BindAddress: "*",
|
||||||
ForceCertVerify: false,
|
Mode: T.Rule,
|
||||||
BindAddress: "*",
|
GeodataMode: C.GeodataMode,
|
||||||
Mode: T.Rule,
|
GeodataLoader: "memconservative",
|
||||||
Authentication: []string{},
|
UnifiedDelay: false,
|
||||||
LogLevel: log.INFO,
|
Authentication: []string{},
|
||||||
Hosts: map[string]string{},
|
LogLevel: log.INFO,
|
||||||
Rule: []string{},
|
Hosts: map[string]string{},
|
||||||
Proxy: []map[string]any{},
|
Rule: []string{},
|
||||||
ProxyGroup: []map[string]any{},
|
Proxy: []map[string]any{},
|
||||||
Tun: Tun{
|
ProxyGroup: []map[string]any{},
|
||||||
Enable: false,
|
TCPConcurrent: false,
|
||||||
Device: "",
|
Tun: RawTun{
|
||||||
Stack: C.TunGvisor,
|
Enable: false,
|
||||||
DNSHijack: []C.DNSUrl{ // default hijack all dns lookup
|
Device: "",
|
||||||
{
|
AutoDetectInterface: true,
|
||||||
Network: "udp",
|
Stack: C.TunGvisor,
|
||||||
AddrPort: C.DNSAddrPort{
|
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
|
||||||
AddrPort: netip.MustParseAddrPort("0.0.0.0:53"),
|
AutoRoute: true,
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Network: "tcp",
|
|
||||||
AddrPort: C.DNSAddrPort{
|
|
||||||
AddrPort: netip.MustParseAddrPort("0.0.0.0:53"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
AutoRoute: false,
|
|
||||||
AutoDetectInterface: false,
|
|
||||||
},
|
},
|
||||||
IPTables: IPTables{
|
IPTables: IPTables{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
InboundInterface: "lo",
|
InboundInterface: "lo",
|
||||||
|
Bypass: []string{},
|
||||||
},
|
},
|
||||||
DNS: RawDNS{
|
DNS: RawDNS{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
@ -262,15 +287,27 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
DefaultNameserver: []string{
|
DefaultNameserver: []string{
|
||||||
"114.114.114.114",
|
"114.114.114.114",
|
||||||
"223.5.5.5",
|
"223.5.5.5",
|
||||||
|
"8.8.8.8",
|
||||||
|
"1.0.0.1",
|
||||||
},
|
},
|
||||||
NameServer: []string{ // default if user not set
|
NameServer: []string{
|
||||||
"https://120.53.53.53/dns-query",
|
"https://doh.pub/dns-query",
|
||||||
"tls://223.5.5.5:853",
|
"tls://223.5.5.5:853",
|
||||||
},
|
},
|
||||||
|
FakeIPFilter: []string{
|
||||||
|
"dns.msftnsci.com",
|
||||||
|
"www.msftnsci.com",
|
||||||
|
"www.msftconnecttest.com",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
MITM: RawMitm{
|
Sniffer: SnifferRaw{
|
||||||
Hosts: []string{},
|
Enable: false,
|
||||||
Rules: []string{},
|
Force: false,
|
||||||
|
Sniffing: []string{},
|
||||||
|
Reverse: []string{},
|
||||||
|
ForceDomain: []string{},
|
||||||
|
SkipSNI: []string{},
|
||||||
|
Ports: []string{},
|
||||||
},
|
},
|
||||||
Profile: Profile{
|
Profile: Profile{
|
||||||
StoreSelected: true,
|
StoreSelected: true,
|
||||||
@ -286,7 +323,8 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
|
|
||||||
func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||||
config := &Config{}
|
config := &Config{}
|
||||||
|
log.Infoln("Start initial configuration in progress") //Segment finished in xxm
|
||||||
|
startTime := time.Now()
|
||||||
config.Experimental = &rawCfg.Experimental
|
config.Experimental = &rawCfg.Experimental
|
||||||
config.Profile = &rawCfg.Profile
|
config.Profile = &rawCfg.Profile
|
||||||
config.IPTables = &rawCfg.IPTables
|
config.IPTables = &rawCfg.IPTables
|
||||||
@ -297,6 +335,14 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.General = general
|
config.General = general
|
||||||
|
|
||||||
|
tunCfg, err := parseTun(rawCfg.Tun, config.General)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Tun = tunCfg
|
||||||
|
|
||||||
|
dialer.DefaultInterface.Store(config.General.Interface)
|
||||||
|
|
||||||
proxies, providers, err := parseProxies(rawCfg)
|
proxies, providers, err := parseProxies(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -304,11 +350,12 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
config.Proxies = proxies
|
config.Proxies = proxies
|
||||||
config.Providers = providers
|
config.Providers = providers
|
||||||
|
|
||||||
rules, err := parseRules(rawCfg, proxies)
|
rules, ruleProviders, err := parseRules(rawCfg, proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.Rules = rules
|
config.Rules = rules
|
||||||
|
config.RuleProviders = ruleProviders
|
||||||
|
|
||||||
hosts, err := parseHosts(rawCfg)
|
hosts, err := parseHosts(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -322,20 +369,21 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.DNS = dnsCfg
|
config.DNS = dnsCfg
|
||||||
|
|
||||||
mitm, err := parseMitm(rawCfg.MITM)
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
|
config.Sniffer, err = parseSniffer(rawCfg.Sniffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.Mitm = mitm
|
|
||||||
|
|
||||||
config.Users = parseAuthentication(rawCfg.Authentication)
|
|
||||||
|
|
||||||
|
elapsedTime := time.Since(startTime) / time.Millisecond // duration in ms
|
||||||
|
log.Infoln("Initial configuration complete, total time: %dms", elapsedTime) //Segment finished in xxm
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseGeneral(cfg *RawConfig) (*General, error) {
|
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||||
externalUI := cfg.ExternalUI
|
externalUI := cfg.ExternalUI
|
||||||
|
geodata.SetLoader(cfg.GeodataLoader)
|
||||||
// checkout externalUI exist
|
// checkout externalUI exist
|
||||||
if externalUI != "" {
|
if externalUI != "" {
|
||||||
externalUI = C.Path.Resolve(externalUI)
|
externalUI = C.Path.Resolve(externalUI)
|
||||||
@ -345,19 +393,6 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.Tun.Enable && cfg.Tun.AutoDetectInterface {
|
|
||||||
outboundInterface, err := commons.GetAutoDetectInterface()
|
|
||||||
if err != nil && cfg.Interface == "" {
|
|
||||||
return nil, fmt.Errorf("get auto detect interface fail: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if outboundInterface != "" {
|
|
||||||
cfg.Interface = outboundInterface
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dialer.DefaultInterface.Store(cfg.Interface)
|
|
||||||
|
|
||||||
return &General{
|
return &General{
|
||||||
Inbound: Inbound{
|
Inbound: Inbound{
|
||||||
Port: cfg.Port,
|
Port: cfg.Port,
|
||||||
@ -365,7 +400,6 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
RedirPort: cfg.RedirPort,
|
RedirPort: cfg.RedirPort,
|
||||||
TProxyPort: cfg.TProxyPort,
|
TProxyPort: cfg.TProxyPort,
|
||||||
MixedPort: cfg.MixedPort,
|
MixedPort: cfg.MixedPort,
|
||||||
MitmPort: cfg.MitmPort,
|
|
||||||
AllowLan: cfg.AllowLan,
|
AllowLan: cfg.AllowLan,
|
||||||
BindAddress: cfg.BindAddress,
|
BindAddress: cfg.BindAddress,
|
||||||
},
|
},
|
||||||
@ -374,13 +408,15 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
ExternalUI: cfg.ExternalUI,
|
ExternalUI: cfg.ExternalUI,
|
||||||
Secret: cfg.Secret,
|
Secret: cfg.Secret,
|
||||||
},
|
},
|
||||||
Mode: cfg.Mode,
|
UnifiedDelay: cfg.UnifiedDelay,
|
||||||
LogLevel: cfg.LogLevel,
|
Mode: cfg.Mode,
|
||||||
IPv6: cfg.IPv6,
|
LogLevel: cfg.LogLevel,
|
||||||
Interface: cfg.Interface,
|
IPv6: cfg.IPv6,
|
||||||
RoutingMark: cfg.RoutingMark,
|
Interface: cfg.Interface,
|
||||||
Sniffing: cfg.Sniffing,
|
RoutingMark: cfg.RoutingMark,
|
||||||
Tun: cfg.Tun,
|
GeodataMode: cfg.GeodataMode,
|
||||||
|
GeodataLoader: cfg.GeodataLoader,
|
||||||
|
TCPConcurrent: cfg.TCPConcurrent,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -390,17 +426,20 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
proxiesConfig := cfg.Proxy
|
proxiesConfig := cfg.Proxy
|
||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
providersConfig := cfg.ProxyProvider
|
providersConfig := cfg.ProxyProvider
|
||||||
forceCertVerify := cfg.ForceCertVerify
|
|
||||||
|
|
||||||
var proxyList []string
|
var proxyList []string
|
||||||
|
_proxiesList := list.New()
|
||||||
|
_groupsList := list.New()
|
||||||
|
|
||||||
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
|
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
|
||||||
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
|
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
|
||||||
|
proxies["COMPATIBLE"] = adapter.NewProxy(outbound.NewCompatible())
|
||||||
|
proxies["PASS"] = adapter.NewProxy(outbound.NewPass())
|
||||||
proxyList = append(proxyList, "DIRECT", "REJECT")
|
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||||
|
|
||||||
// parse proxy
|
// parse proxy
|
||||||
for idx, mapping := range proxiesConfig {
|
for idx, mapping := range proxiesConfig {
|
||||||
proxy, err := adapter.ParseProxy(mapping, forceCertVerify)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("proxy %d: %w", idx, err)
|
return nil, nil, fmt.Errorf("proxy %d: %w", idx, err)
|
||||||
}
|
}
|
||||||
@ -410,6 +449,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
}
|
}
|
||||||
proxies[proxy.Name()] = proxy
|
proxies[proxy.Name()] = proxy
|
||||||
proxyList = append(proxyList, proxy.Name())
|
proxyList = append(proxyList, proxy.Name())
|
||||||
|
_proxiesList.PushBack(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// keep the original order of ProxyGroups in config file
|
// keep the original order of ProxyGroups in config file
|
||||||
@ -419,6 +459,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
||||||
}
|
}
|
||||||
proxyList = append(proxyList, groupName)
|
proxyList = append(proxyList, groupName)
|
||||||
|
_groupsList.PushBack(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if any loop exists and sort the ProxyGroups
|
// check if any loop exists and sort the ProxyGroups
|
||||||
@ -432,7 +473,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
return nil, nil, fmt.Errorf("can not defined a provider called `%s`", provider.ReservedName)
|
return nil, nil, fmt.Errorf("can not defined a provider called `%s`", provider.ReservedName)
|
||||||
}
|
}
|
||||||
|
|
||||||
pd, err := provider.ParseProxyProvider(name, mapping, forceCertVerify)
|
pd, err := provider.ParseProxyProvider(name, mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("parse proxy provider %s error: %w", name, err)
|
return nil, nil, fmt.Errorf("parse proxy provider %s error: %w", name, err)
|
||||||
}
|
}
|
||||||
@ -440,13 +481,6 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
providersMap[name] = pd
|
providersMap[name] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, proxyProvider := range providersMap {
|
|
||||||
log.Infoln("Start initial proxy provider %s", proxyProvider.Name())
|
|
||||||
if err := proxyProvider.Initial(); err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("initial proxy provider %s error: %w", proxyProvider.Name(), err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse proxy group
|
// parse proxy group
|
||||||
for idx, mapping := range groupsConfig {
|
for idx, mapping := range groupsConfig {
|
||||||
group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap)
|
group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap)
|
||||||
@ -462,20 +496,11 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
proxies[groupName] = adapter.NewProxy(group)
|
proxies[groupName] = adapter.NewProxy(group)
|
||||||
}
|
}
|
||||||
|
|
||||||
// initial compatible provider
|
|
||||||
for _, pd := range providersMap {
|
|
||||||
if pd.VehicleType() != providerTypes.Compatible {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Infoln("Start initial compatible provider %s", pd.Name())
|
|
||||||
if err := pd.Initial(); err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var ps []C.Proxy
|
var ps []C.Proxy
|
||||||
for _, v := range proxyList {
|
for _, v := range proxyList {
|
||||||
|
if proxies[v].Type() == C.Pass {
|
||||||
|
continue
|
||||||
|
}
|
||||||
ps = append(ps, proxies[v])
|
ps = append(ps, proxies[v])
|
||||||
}
|
}
|
||||||
hc := provider.NewHealthCheck(ps, "", 0, true)
|
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||||
@ -489,13 +514,32 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
[]providerTypes.ProxyProvider{pd},
|
[]providerTypes.ProxyProvider{pd},
|
||||||
)
|
)
|
||||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||||
|
ProxiesList = _proxiesList
|
||||||
|
GroupsList = _groupsList
|
||||||
|
if ParsingProxiesCallback != nil {
|
||||||
|
// refresh tray menu
|
||||||
|
go ParsingProxiesCallback(GroupsList, ProxiesList)
|
||||||
|
}
|
||||||
return proxies, providersMap, nil
|
return proxies, providersMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[string]providerTypes.RuleProvider, error) {
|
||||||
rulesConfig := cfg.Rule
|
ruleProviders := map[string]providerTypes.RuleProvider{}
|
||||||
|
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
|
||||||
|
// parse rule provider
|
||||||
|
for name, mapping := range cfg.RuleProvider {
|
||||||
|
rp, err := RP.ParseRuleProvider(name, mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ruleProviders[name] = rp
|
||||||
|
RP.SetRuleProvider(rp)
|
||||||
|
}
|
||||||
|
|
||||||
var rules []C.Rule
|
var rules []C.Rule
|
||||||
|
rulesConfig := cfg.Rule
|
||||||
|
mode := cfg.Mode
|
||||||
|
|
||||||
// parse rules
|
// parse rules
|
||||||
for idx, line := range rulesConfig {
|
for idx, line := range rulesConfig {
|
||||||
@ -507,37 +551,48 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
|||||||
ruleName = strings.ToUpper(rule[0])
|
ruleName = strings.ToUpper(rule[0])
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if mode == T.Script && ruleName != "GEOSITE" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
l := len(rule)
|
l := len(rule)
|
||||||
|
|
||||||
if l < 2 {
|
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" {
|
||||||
return nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
|
target = rule[l-1]
|
||||||
|
payload = strings.Join(rule[1:l-1], ",")
|
||||||
|
} else {
|
||||||
|
if l < 2 {
|
||||||
|
return nil, nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
|
||||||
|
}
|
||||||
|
if l < 4 {
|
||||||
|
rule = append(rule, make([]string, 4-l)...)
|
||||||
|
}
|
||||||
|
if ruleName == "MATCH" {
|
||||||
|
l = 2
|
||||||
|
}
|
||||||
|
if l >= 3 {
|
||||||
|
l = 3
|
||||||
|
payload = rule[1]
|
||||||
|
}
|
||||||
|
target = rule[l-1]
|
||||||
|
params = rule[l:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if l < 4 {
|
|
||||||
rule = append(rule, make([]string, 4-l)...)
|
|
||||||
}
|
|
||||||
|
|
||||||
if ruleName == "MATCH" {
|
|
||||||
l = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
if l >= 3 {
|
|
||||||
l = 3
|
|
||||||
payload = rule[1]
|
|
||||||
}
|
|
||||||
|
|
||||||
target = rule[l-1]
|
|
||||||
params = rule[l:]
|
|
||||||
|
|
||||||
if _, ok := proxies[target]; !ok {
|
if _, ok := proxies[target]; !ok {
|
||||||
return nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
return nil, nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
||||||
}
|
}
|
||||||
|
|
||||||
params = trimArr(params)
|
params = trimArr(params)
|
||||||
|
|
||||||
|
if ruleName == "GEOSITE" {
|
||||||
|
if err := initGeoSite(); err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
||||||
|
}
|
||||||
|
initMode = false
|
||||||
|
}
|
||||||
parsed, parseErr := R.ParseRule(ruleName, payload, target, params)
|
parsed, parseErr := R.ParseRule(ruleName, payload, target, params)
|
||||||
if parseErr != nil {
|
if parseErr != nil {
|
||||||
return nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
return nil, nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
rules = append(rules, parsed)
|
rules = append(rules, parsed)
|
||||||
@ -545,7 +600,7 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
|||||||
|
|
||||||
runtime.GC()
|
runtime.GC()
|
||||||
|
|
||||||
return rules, nil
|
return rules, ruleProviders, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseHosts(cfg *RawConfig) (*trie.DomainTrie[netip.Addr], error) {
|
func parseHosts(cfg *RawConfig) (*trie.DomainTrie[netip.Addr], error) {
|
||||||
@ -566,11 +621,6 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie[netip.Addr], error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// add mitm.clash hosts
|
|
||||||
if err := tree.Insert("mitm.clash", netip.AddrFrom4([4]byte{1, 2, 3, 4})); err != nil {
|
|
||||||
log.Errorln("insert mitm.clash to host error: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return tree, nil
|
return tree, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -622,6 +672,9 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
case "dhcp":
|
case "dhcp":
|
||||||
addr = u.Host
|
addr = u.Host
|
||||||
dnsNetType = "dhcp" // UDP from DHCP
|
dnsNetType = "dhcp" // UDP from DHCP
|
||||||
|
case "quic":
|
||||||
|
addr, err = hostWithDefaultPort(u.Host, "784")
|
||||||
|
dnsNetType = "quic" // DNS over QUIC
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||||
}
|
}
|
||||||
@ -636,7 +689,7 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
Net: dnsNetType,
|
Net: dnsNetType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
ProxyAdapter: u.Fragment,
|
ProxyAdapter: u.Fragment,
|
||||||
Interface: dialer.DefaultInterface.Load(),
|
Interface: dialer.DefaultInterface,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -676,6 +729,11 @@ func parseFallbackIPCIDR(ips []string) ([]*netip.Prefix, error) {
|
|||||||
|
|
||||||
func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) {
|
func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) {
|
||||||
var sites []*router.DomainMatcher
|
var sites []*router.DomainMatcher
|
||||||
|
if len(countries) > 0 {
|
||||||
|
if err := initGeoSite(); err != nil {
|
||||||
|
return nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for _, country := range countries {
|
for _, country := range countries {
|
||||||
found := false
|
found := false
|
||||||
@ -747,7 +805,10 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie[netip.Addr], rules []C.R
|
|||||||
for _, ns := range dnsCfg.DefaultNameserver {
|
for _, ns := range dnsCfg.DefaultNameserver {
|
||||||
host, _, err := net.SplitHostPort(ns.Addr)
|
host, _, err := net.SplitHostPort(ns.Addr)
|
||||||
if err != nil || net.ParseIP(host) == nil {
|
if err != nil || net.ParseIP(host) == nil {
|
||||||
return nil, errors.New("default nameserver should be pure IP")
|
u, err := url.Parse(ns.Addr)
|
||||||
|
if err != nil || net.ParseIP(u.Host) == nil {
|
||||||
|
return nil, errors.New("default nameserver should be pure IP")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -822,37 +883,134 @@ func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
|||||||
return users
|
return users
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseMitm(rawMitm RawMitm) (*Mitm, error) {
|
func parseTun(rawTun RawTun, general *General) (*Tun, error) {
|
||||||
var (
|
if rawTun.Enable && rawTun.AutoDetectInterface {
|
||||||
req []C.Rewrite
|
autoDetectInterfaceName, err := commons.GetAutoDetectInterface()
|
||||||
res []C.Rewrite
|
|
||||||
)
|
|
||||||
|
|
||||||
for _, line := range rawMitm.Rules {
|
|
||||||
rule, err := rewrites.ParseRewrite(line)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("parse rewrite rule failure: %w", err)
|
log.Warnln("Can not find auto detect interface.[%s]", err)
|
||||||
}
|
|
||||||
|
|
||||||
if rule.RuleType() == C.MitmResponseHeader || rule.RuleType() == C.MitmResponseBody {
|
|
||||||
res = append(res, rule)
|
|
||||||
} else {
|
} else {
|
||||||
req = append(req, rule)
|
log.Warnln("Auto detect interface: %s", autoDetectInterfaceName)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
general.Interface = autoDetectInterfaceName
|
||||||
}
|
}
|
||||||
|
|
||||||
hosts := trie.New[bool]()
|
var dnsHijack []netip.AddrPort
|
||||||
|
|
||||||
if len(rawMitm.Hosts) != 0 {
|
for _, d := range rawTun.DNSHijack {
|
||||||
for _, domain := range rawMitm.Hosts {
|
if _, after, ok := strings.Cut(d, "://"); ok {
|
||||||
_ = hosts.Insert(domain, true)
|
d = after
|
||||||
}
|
}
|
||||||
|
d = strings.Replace(d, "any", "0.0.0.0", 1)
|
||||||
|
addrPort, err := netip.ParseAddrPort(d)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse dns-hijack url error: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsHijack = append(dnsHijack, addrPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = hosts.Insert("mitm.clash", true)
|
return &Tun{
|
||||||
|
Enable: rawTun.Enable,
|
||||||
return &Mitm{
|
Device: rawTun.Device,
|
||||||
Hosts: hosts,
|
Stack: rawTun.Stack,
|
||||||
Rules: rewrites.NewRewriteRules(req, res),
|
DNSHijack: dnsHijack,
|
||||||
|
AutoRoute: rawTun.AutoRoute,
|
||||||
|
AutoDetectInterface: rawTun.AutoDetectInterface,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseSniffer(snifferRaw SnifferRaw) (*Sniffer, error) {
|
||||||
|
sniffer := &Sniffer{
|
||||||
|
Enable: snifferRaw.Enable,
|
||||||
|
Force: snifferRaw.Force,
|
||||||
|
}
|
||||||
|
|
||||||
|
var ports []utils.Range[uint16]
|
||||||
|
if len(snifferRaw.Ports) == 0 {
|
||||||
|
ports = append(ports, *utils.NewRange[uint16](0, 65535))
|
||||||
|
} else {
|
||||||
|
for _, portRange := range snifferRaw.Ports {
|
||||||
|
portRaws := strings.Split(portRange, "-")
|
||||||
|
p, err := strconv.ParseUint(portRaws[0], 10, 16)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s format error", portRange)
|
||||||
|
}
|
||||||
|
|
||||||
|
start := uint16(p)
|
||||||
|
if len(portRaws) > 1 {
|
||||||
|
p, err = strconv.ParseUint(portRaws[1], 10, 16)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s format error", portRange)
|
||||||
|
}
|
||||||
|
|
||||||
|
end := uint16(p)
|
||||||
|
ports = append(ports, *utils.NewRange(start, end))
|
||||||
|
} else {
|
||||||
|
ports = append(ports, *utils.NewRange(start, start))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sniffer.Ports = &ports
|
||||||
|
|
||||||
|
loadSniffer := make(map[C.SnifferType]struct{})
|
||||||
|
|
||||||
|
for _, snifferName := range snifferRaw.Sniffing {
|
||||||
|
find := false
|
||||||
|
for _, snifferType := range C.SnifferList {
|
||||||
|
if snifferType.String() == strings.ToUpper(snifferName) {
|
||||||
|
find = true
|
||||||
|
loadSniffer[snifferType] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !find {
|
||||||
|
return nil, fmt.Errorf("not find the sniffer[%s]", snifferName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for st := range loadSniffer {
|
||||||
|
sniffer.Sniffers = append(sniffer.Sniffers, st)
|
||||||
|
}
|
||||||
|
|
||||||
|
sniffer.ForceDomain = trie.New[bool]()
|
||||||
|
for _, domain := range snifferRaw.ForceDomain {
|
||||||
|
err := sniffer.ForceDomain.Insert(domain, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error domian[%s] in force-domain, error:%v", domain, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sniffer.SkipSNI = trie.New[bool]()
|
||||||
|
for _, domain := range snifferRaw.SkipSNI {
|
||||||
|
err := sniffer.SkipSNI.Insert(domain, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error domian[%s] in force-domain, error:%v", domain, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compatibility, remove it when release
|
||||||
|
if strings.Contains(C.Version, "alpha") || strings.Contains(C.Version, "develop") || strings.Contains(C.Version, "1.10.0") {
|
||||||
|
log.Warnln("Sniffer param force and reverses deprecated, will be removed in the release version, see https://github.com/MetaCubeX/Clash.Meta/commit/48a01adb7a4f38974b9d9639f931d0d245aebf28")
|
||||||
|
if snifferRaw.Force {
|
||||||
|
// match all domain
|
||||||
|
sniffer.ForceDomain.Insert("+", true)
|
||||||
|
for _, domain := range snifferRaw.Reverse {
|
||||||
|
err := sniffer.SkipSNI.Insert(domain, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error domian[%s], error:%v", domain, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, domain := range snifferRaw.Reverse {
|
||||||
|
err := sniffer.ForceDomain.Insert(domain, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error domian[%s], error:%v", domain, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sniffer, nil
|
||||||
|
}
|
||||||
|
@ -2,18 +2,20 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/geodata"
|
||||||
|
"github.com/Dreamacro/clash/component/mmdb"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
"github.com/Dreamacro/clash/component/mmdb"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var initMode = true
|
||||||
|
|
||||||
func downloadMMDB(path string) (err error) {
|
func downloadMMDB(path string) (err error) {
|
||||||
resp, err := doGet("https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb")
|
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/geoip/release/Country.mmdb")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -29,30 +31,25 @@ func downloadMMDB(path string) (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func initMMDB() error {
|
func downloadGeoIP(path string) (err error) {
|
||||||
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/v2ray-rules-dat/release/geoip.dat")
|
||||||
log.Infoln("Can't find MMDB, start download")
|
if err != nil {
|
||||||
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
return
|
||||||
return fmt.Errorf("can't download MMDB: %w", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if !mmdb.Verify() {
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
log.Warnln("MMDB invalid, remove and download")
|
if err != nil {
|
||||||
if err := os.Remove(C.Path.MMDB()); err != nil {
|
return err
|
||||||
return fmt.Errorf("can't remove invalid MMDB: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
|
||||||
return fmt.Errorf("can't download MMDB: %w", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
return nil
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadGeoSite(path string) (err error) {
|
func downloadGeoSite(path string) (err error) {
|
||||||
resp, err := doGet("https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat")
|
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/v2ray-rules-dat/release/geosite.dat")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -72,10 +69,63 @@ func initGeoSite() error {
|
|||||||
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
||||||
log.Infoln("Can't find GeoSite.dat, start download")
|
log.Infoln("Can't find GeoSite.dat, start download")
|
||||||
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
||||||
return fmt.Errorf("can't download GeoSite.dat: %w", err)
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
}
|
}
|
||||||
log.Infoln("Download GeoSite.dat finish")
|
log.Infoln("Download GeoSite.dat finish")
|
||||||
}
|
}
|
||||||
|
if initMode {
|
||||||
|
if !geodata.Verify(C.GeositeName) {
|
||||||
|
log.Warnln("GeoSite.dat invalid, remove and download")
|
||||||
|
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func initGeoIP() error {
|
||||||
|
if C.GeodataMode {
|
||||||
|
if _, err := os.Stat(C.Path.GeoIP()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find GeoIP.dat, start download")
|
||||||
|
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
log.Infoln("Download GeoIP.dat finish")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !geodata.Verify(C.GeoipName) {
|
||||||
|
log.Warnln("GeoIP.dat invalid, remove and download")
|
||||||
|
if err := os.Remove(C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid GeoIP.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find MMDB, start download")
|
||||||
|
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't download MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !mmdb.Verify() {
|
||||||
|
log.Warnln("MMDB invalid, remove and download")
|
||||||
|
if err := os.Remove(C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't download MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -85,7 +135,7 @@ func Init(dir string) error {
|
|||||||
// initial homedir
|
// initial homedir
|
||||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
if err := os.MkdirAll(dir, 0o777); err != nil {
|
if err := os.MkdirAll(dir, 0o777); err != nil {
|
||||||
return fmt.Errorf("can't create config directory %s: %w", dir, err)
|
return fmt.Errorf("can't create config directory %s: %s", dir, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -94,33 +144,25 @@ func Init(dir string) error {
|
|||||||
log.Infoln("Can't find config, create a initial config file")
|
log.Infoln("Can't find config, create a initial config file")
|
||||||
f, err := os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0o644)
|
f, err := os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("can't create file %s: %w", C.Path.Config(), err)
|
return fmt.Errorf("can't create file %s: %s", C.Path.Config(), err.Error())
|
||||||
}
|
}
|
||||||
_, _ = f.Write([]byte(`mixed-port: 7890`))
|
f.Write([]byte(`mixed-port: 7890`))
|
||||||
_ = f.Close()
|
f.Close()
|
||||||
|
}
|
||||||
|
buf, _ := os.ReadFile(C.Path.Config())
|
||||||
|
rawCfg, err := UnmarshalRawConfig(buf)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln(err.Error())
|
||||||
|
fmt.Printf("configuration file %s test failed\n", C.Path.Config())
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if !C.GeodataMode {
|
||||||
|
C.GeodataMode = rawCfg.GeodataMode
|
||||||
|
}
|
||||||
|
// initial GeoIP
|
||||||
|
if err := initGeoIP(); err != nil {
|
||||||
|
return fmt.Errorf("can't initial GeoIP: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// initial mmdb
|
|
||||||
if err := initMMDB(); err != nil {
|
|
||||||
return fmt.Errorf("can't initial MMDB: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// initial GeoSite
|
|
||||||
if err := initGeoSite(); err != nil {
|
|
||||||
return fmt.Errorf("can't initial GeoSite: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func doGet(url string) (resp *http.Response, err error) {
|
|
||||||
var req *http.Request
|
|
||||||
req, err = http.NewRequest("GET", url, nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
convert.SetUserAgent(req)
|
|
||||||
|
|
||||||
resp, err = http.DefaultClient.Do(req)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
@ -1,69 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata"
|
|
||||||
_ "github.com/Dreamacro/clash/component/geodata/standard"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"github.com/oschwald/geoip2-golang"
|
|
||||||
)
|
|
||||||
|
|
||||||
func UpdateGeoDatabases() error {
|
|
||||||
var (
|
|
||||||
tmpMMDB = C.Path.Resolve("temp_country.mmdb")
|
|
||||||
tmpGeoSite = C.Path.Resolve("temp_geosite.dat")
|
|
||||||
)
|
|
||||||
|
|
||||||
if err := downloadMMDB(tmpMMDB); err != nil {
|
|
||||||
return fmt.Errorf("can't download MMDB database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := verifyMMDB(tmpMMDB); err != nil {
|
|
||||||
_ = os.Remove(tmpMMDB)
|
|
||||||
return fmt.Errorf("invalid MMDB database file, %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := os.Rename(tmpMMDB, C.Path.MMDB()); err != nil {
|
|
||||||
return fmt.Errorf("can't rename MMDB database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := downloadGeoSite(tmpGeoSite); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoSite database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := verifyGeoSite(tmpGeoSite); err != nil {
|
|
||||||
_ = os.Remove(tmpGeoSite)
|
|
||||||
return fmt.Errorf("invalid GeoSite database file, %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := os.Rename(tmpGeoSite, C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't rename GeoSite database file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func verifyMMDB(path string) error {
|
|
||||||
instance, err := geoip2.Open(path)
|
|
||||||
if err == nil {
|
|
||||||
_ = instance.Close()
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func verifyGeoSite(path string) error {
|
|
||||||
geoLoader, err := geodata.GetGeoDataLoader("standard")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = geoLoader.LoadSite(path, "cn")
|
|
||||||
|
|
||||||
runtime.GC()
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
@ -13,7 +13,14 @@ import (
|
|||||||
const (
|
const (
|
||||||
Direct AdapterType = iota
|
Direct AdapterType = iota
|
||||||
Reject
|
Reject
|
||||||
Mitm
|
Compatible
|
||||||
|
Pass
|
||||||
|
|
||||||
|
Relay
|
||||||
|
Selector
|
||||||
|
Fallback
|
||||||
|
URLTest
|
||||||
|
LoadBalance
|
||||||
|
|
||||||
Shadowsocks
|
Shadowsocks
|
||||||
ShadowsocksR
|
ShadowsocksR
|
||||||
@ -23,12 +30,6 @@ const (
|
|||||||
Vmess
|
Vmess
|
||||||
Vless
|
Vless
|
||||||
Trojan
|
Trojan
|
||||||
|
|
||||||
Relay
|
|
||||||
Selector
|
|
||||||
Fallback
|
|
||||||
URLTest
|
|
||||||
LoadBalance
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -93,16 +94,15 @@ type ProxyAdapter interface {
|
|||||||
// a new session (if any)
|
// a new session (if any)
|
||||||
StreamConn(c net.Conn, metadata *Metadata) (net.Conn, error)
|
StreamConn(c net.Conn, metadata *Metadata) (net.Conn, error)
|
||||||
|
|
||||||
// StreamPacketConn wraps a UDP protocol around net.Conn with Metadata.
|
|
||||||
StreamPacketConn(c net.Conn, metadata *Metadata) (net.Conn, error)
|
|
||||||
|
|
||||||
// DialContext return a C.Conn with protocol which
|
// DialContext return a C.Conn with protocol which
|
||||||
// contains multiplexing-related reuse logic (if any)
|
// contains multiplexing-related reuse logic (if any)
|
||||||
DialContext(ctx context.Context, metadata *Metadata, opts ...dialer.Option) (Conn, error)
|
DialContext(ctx context.Context, metadata *Metadata, opts ...dialer.Option) (Conn, error)
|
||||||
|
|
||||||
// ListenPacketContext listen for a PacketConn
|
|
||||||
ListenPacketContext(ctx context.Context, metadata *Metadata, opts ...dialer.Option) (PacketConn, error)
|
ListenPacketContext(ctx context.Context, metadata *Metadata, opts ...dialer.Option) (PacketConn, error)
|
||||||
|
|
||||||
|
// SupportUOT return UDP over TCP support
|
||||||
|
SupportUOT() bool
|
||||||
|
ListenPacketOnStreamConn(c net.Conn, metadata *Metadata) (PacketConn, error)
|
||||||
|
|
||||||
// Unwrap extracts the proxy from a proxy-group. It returns nil when nothing to extract.
|
// Unwrap extracts the proxy from a proxy-group. It returns nil when nothing to extract.
|
||||||
Unwrap(metadata *Metadata) Proxy
|
Unwrap(metadata *Metadata) Proxy
|
||||||
}
|
}
|
||||||
@ -135,9 +135,10 @@ func (at AdapterType) String() string {
|
|||||||
return "Direct"
|
return "Direct"
|
||||||
case Reject:
|
case Reject:
|
||||||
return "Reject"
|
return "Reject"
|
||||||
case Mitm:
|
case Compatible:
|
||||||
return "Mitm"
|
return "Compatible"
|
||||||
|
case Pass:
|
||||||
|
return "Pass"
|
||||||
case Shadowsocks:
|
case Shadowsocks:
|
||||||
return "Shadowsocks"
|
return "Shadowsocks"
|
||||||
case ShadowsocksR:
|
case ShadowsocksR:
|
||||||
|
3
constant/geodata.go
Normal file
3
constant/geodata.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package constant
|
||||||
|
|
||||||
|
var GeodataMode bool
|
@ -2,6 +2,7 @@ package constant
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -24,7 +25,7 @@ const (
|
|||||||
REDIR
|
REDIR
|
||||||
TPROXY
|
TPROXY
|
||||||
TUN
|
TUN
|
||||||
MITM
|
INNER
|
||||||
)
|
)
|
||||||
|
|
||||||
type NetWork int
|
type NetWork int
|
||||||
@ -60,8 +61,8 @@ func (t Type) String() string {
|
|||||||
return "TProxy"
|
return "TProxy"
|
||||||
case TUN:
|
case TUN:
|
||||||
return "Tun"
|
return "Tun"
|
||||||
case MITM:
|
case INNER:
|
||||||
return "Mitm"
|
return "Inner"
|
||||||
default:
|
default:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
@ -82,9 +83,9 @@ type Metadata struct {
|
|||||||
AddrType int `json:"-"`
|
AddrType int `json:"-"`
|
||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
DNSMode DNSMode `json:"dnsMode"`
|
DNSMode DNSMode `json:"dnsMode"`
|
||||||
|
Uid *int32 `json:"uid"`
|
||||||
Process string `json:"process"`
|
Process string `json:"process"`
|
||||||
ProcessPath string `json:"processPath"`
|
ProcessPath string `json:"processPath"`
|
||||||
UserAgent string `json:"userAgent"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Metadata) RemoteAddress() string {
|
func (m *Metadata) RemoteAddress() string {
|
||||||
@ -95,14 +96,30 @@ func (m *Metadata) SourceAddress() string {
|
|||||||
return net.JoinHostPort(m.SrcIP.String(), m.SrcPort)
|
return net.JoinHostPort(m.SrcIP.String(), m.SrcPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *Metadata) SourceDetail() string {
|
||||||
|
if m.Type == INNER {
|
||||||
|
return fmt.Sprintf("[%s]", ClashName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.Process != "" && m.Uid != nil {
|
||||||
|
return fmt.Sprintf("%s(%s, uid=%d)", m.SourceAddress(), m.Process, *m.Uid)
|
||||||
|
} else if m.Uid != nil {
|
||||||
|
return fmt.Sprintf("%s(%d)", m.SourceAddress(), *m.Uid)
|
||||||
|
} else if m.Process != "" {
|
||||||
|
return fmt.Sprintf("%s(%s)", m.SourceAddress(), m.Process)
|
||||||
|
} else {
|
||||||
|
return fmt.Sprintf("%s", m.SourceAddress())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (m *Metadata) Resolved() bool {
|
func (m *Metadata) Resolved() bool {
|
||||||
return m.DstIP.IsValid()
|
return m.DstIP.IsValid()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pure is used to solve unexpected behavior
|
// Pure is used to solve unexpected behavior
|
||||||
// when dialing proxy connection in DNSMapping mode.
|
// when dialing proxy connection in DNSMapping mode.
|
||||||
func (m *Metadata) Pure(isMitmOutbound bool) *Metadata {
|
func (m *Metadata) Pure() *Metadata {
|
||||||
if !isMitmOutbound && m.DNSMode == DNSMapping && m.DstIP.IsValid() {
|
if m.DNSMode == DNSMapping && m.DstIP.IsValid() {
|
||||||
copyM := *m
|
copyM := *m
|
||||||
copyM.Host = ""
|
copyM.Host = ""
|
||||||
if copyM.DstIP.Is4() {
|
if copyM.DstIP.Is4() {
|
||||||
|
@ -1,13 +1,20 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
P "path"
|
P "path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
const Name = "clash"
|
const Name = "clash"
|
||||||
|
|
||||||
|
var (
|
||||||
|
GeositeName = "GeoSite.dat"
|
||||||
|
GeoipName = "GeoIP.dat"
|
||||||
|
)
|
||||||
|
|
||||||
// Path is used to get the configuration path
|
// Path is used to get the configuration path
|
||||||
var Path = func() *path {
|
var Path = func() *path {
|
||||||
homeDir, err := os.UserHomeDir()
|
homeDir, err := os.UserHomeDir()
|
||||||
@ -22,6 +29,7 @@ var Path = func() *path {
|
|||||||
type path struct {
|
type path struct {
|
||||||
homeDir string
|
homeDir string
|
||||||
configFile string
|
configFile string
|
||||||
|
scriptDir string
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetHomeDir is used to set the configuration path
|
// SetHomeDir is used to set the configuration path
|
||||||
@ -47,11 +55,25 @@ func (p *path) Resolve(path string) string {
|
|||||||
if !filepath.IsAbs(path) {
|
if !filepath.IsAbs(path) {
|
||||||
return filepath.Join(p.HomeDir(), path)
|
return filepath.Join(p.HomeDir(), path)
|
||||||
}
|
}
|
||||||
|
|
||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) MMDB() string {
|
func (p *path) MMDB() string {
|
||||||
|
files, err := ioutil.ReadDir(p.homeDir)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, fi := range files {
|
||||||
|
if fi.IsDir() {
|
||||||
|
// 目录则直接跳过
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
if strings.EqualFold(fi.Name(), "Country.mmdb") {
|
||||||
|
GeoipName = fi.Name()
|
||||||
|
return P.Join(p.homeDir, fi.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return P.Join(p.homeDir, "Country.mmdb")
|
return P.Join(p.homeDir, "Country.mmdb")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -64,17 +86,69 @@ func (p *path) Cache() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) GeoIP() string {
|
func (p *path) GeoIP() string {
|
||||||
return P.Join(p.homeDir, "geoip.dat")
|
files, err := ioutil.ReadDir(p.homeDir)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, fi := range files {
|
||||||
|
if fi.IsDir() {
|
||||||
|
// 目录则直接跳过
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
if strings.EqualFold(fi.Name(), "GeoIP.dat") {
|
||||||
|
GeoipName = fi.Name()
|
||||||
|
return P.Join(p.homeDir, fi.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return P.Join(p.homeDir, "GeoIP.dat")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) GeoSite() string {
|
func (p *path) GeoSite() string {
|
||||||
return P.Join(p.homeDir, "geosite.dat")
|
files, err := ioutil.ReadDir(p.homeDir)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, fi := range files {
|
||||||
|
if fi.IsDir() {
|
||||||
|
// 目录则直接跳过
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
if strings.EqualFold(fi.Name(), "GeoSite.dat") {
|
||||||
|
GeositeName = fi.Name()
|
||||||
|
return P.Join(p.homeDir, fi.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return P.Join(p.homeDir, "GeoSite.dat")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) RootCA() string {
|
func (p *path) ScriptDir() string {
|
||||||
return p.Resolve("mitm_ca.crt")
|
if len(p.scriptDir) != 0 {
|
||||||
|
return p.scriptDir
|
||||||
|
}
|
||||||
|
if dir, err := os.MkdirTemp("", Name+"-"); err == nil {
|
||||||
|
p.scriptDir = dir
|
||||||
|
} else {
|
||||||
|
p.scriptDir = P.Join(os.TempDir(), Name)
|
||||||
|
_ = os.MkdirAll(p.scriptDir, 0o644)
|
||||||
|
}
|
||||||
|
return p.scriptDir
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) CAKey() string {
|
func (p *path) Script() string {
|
||||||
return p.Resolve("mitm_ca.key")
|
return P.Join(p.ScriptDir(), "clash_script.py")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *path) GetAssetLocation(file string) string {
|
||||||
|
return P.Join(p.homeDir, file)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *path) GetExecutableFullPath() string {
|
||||||
|
exePath, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return "clash"
|
||||||
|
}
|
||||||
|
res, _ := filepath.EvalSymlinks(exePath)
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
|
@ -70,6 +70,7 @@ type ProxyProvider interface {
|
|||||||
// Commonly used in DialContext and DialPacketConn
|
// Commonly used in DialContext and DialPacketConn
|
||||||
ProxiesWithTouch() []constant.Proxy
|
ProxiesWithTouch() []constant.Proxy
|
||||||
HealthCheck()
|
HealthCheck()
|
||||||
|
Version() uint
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rule Type
|
// Rule Type
|
||||||
|
@ -1,82 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"regexp"
|
|
||||||
)
|
|
||||||
|
|
||||||
var RewriteTypeMapping = map[string]RewriteType{
|
|
||||||
MitmReject.String(): MitmReject,
|
|
||||||
MitmReject200.String(): MitmReject200,
|
|
||||||
MitmRejectImg.String(): MitmRejectImg,
|
|
||||||
MitmRejectDict.String(): MitmRejectDict,
|
|
||||||
MitmRejectArray.String(): MitmRejectArray,
|
|
||||||
Mitm302.String(): Mitm302,
|
|
||||||
Mitm307.String(): Mitm307,
|
|
||||||
MitmRequestHeader.String(): MitmRequestHeader,
|
|
||||||
MitmRequestBody.String(): MitmRequestBody,
|
|
||||||
MitmResponseHeader.String(): MitmResponseHeader,
|
|
||||||
MitmResponseBody.String(): MitmResponseBody,
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
MitmReject RewriteType = iota
|
|
||||||
MitmReject200
|
|
||||||
MitmRejectImg
|
|
||||||
MitmRejectDict
|
|
||||||
MitmRejectArray
|
|
||||||
|
|
||||||
Mitm302
|
|
||||||
Mitm307
|
|
||||||
|
|
||||||
MitmRequestHeader
|
|
||||||
MitmRequestBody
|
|
||||||
|
|
||||||
MitmResponseHeader
|
|
||||||
MitmResponseBody
|
|
||||||
)
|
|
||||||
|
|
||||||
type RewriteType int
|
|
||||||
|
|
||||||
func (rt RewriteType) String() string {
|
|
||||||
switch rt {
|
|
||||||
case MitmReject:
|
|
||||||
return "reject" // 404
|
|
||||||
case MitmReject200:
|
|
||||||
return "reject-200"
|
|
||||||
case MitmRejectImg:
|
|
||||||
return "reject-img"
|
|
||||||
case MitmRejectDict:
|
|
||||||
return "reject-dict"
|
|
||||||
case MitmRejectArray:
|
|
||||||
return "reject-array"
|
|
||||||
case Mitm302:
|
|
||||||
return "302"
|
|
||||||
case Mitm307:
|
|
||||||
return "307"
|
|
||||||
case MitmRequestHeader:
|
|
||||||
return "request-header"
|
|
||||||
case MitmRequestBody:
|
|
||||||
return "request-body"
|
|
||||||
case MitmResponseHeader:
|
|
||||||
return "response-header"
|
|
||||||
case MitmResponseBody:
|
|
||||||
return "response-body"
|
|
||||||
default:
|
|
||||||
return "Unknown"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Rewrite interface {
|
|
||||||
ID() string
|
|
||||||
URLRegx() *regexp.Regexp
|
|
||||||
RuleType() RewriteType
|
|
||||||
RuleRegx() *regexp.Regexp
|
|
||||||
RulePayload() string
|
|
||||||
ReplaceURLPayload([]string) string
|
|
||||||
ReplaceSubPayload(string) string
|
|
||||||
}
|
|
||||||
|
|
||||||
type RewriteRule interface {
|
|
||||||
SearchInRequest(func(Rewrite) bool) bool
|
|
||||||
SearchInResponse(func(Rewrite) bool) bool
|
|
||||||
}
|
|
@ -13,8 +13,14 @@ const (
|
|||||||
DstPort
|
DstPort
|
||||||
Process
|
Process
|
||||||
ProcessPath
|
ProcessPath
|
||||||
UserAgent
|
Script
|
||||||
|
RuleSet
|
||||||
|
Network
|
||||||
|
Uid
|
||||||
MATCH
|
MATCH
|
||||||
|
AND
|
||||||
|
OR
|
||||||
|
NOT
|
||||||
)
|
)
|
||||||
|
|
||||||
type RuleType int
|
type RuleType int
|
||||||
@ -43,10 +49,22 @@ func (rt RuleType) String() string {
|
|||||||
return "Process"
|
return "Process"
|
||||||
case ProcessPath:
|
case ProcessPath:
|
||||||
return "ProcessPath"
|
return "ProcessPath"
|
||||||
case UserAgent:
|
case Script:
|
||||||
return "UserAgent"
|
return "Script"
|
||||||
case MATCH:
|
case MATCH:
|
||||||
return "Match"
|
return "Match"
|
||||||
|
case RuleSet:
|
||||||
|
return "RuleSet"
|
||||||
|
case Network:
|
||||||
|
return "Network"
|
||||||
|
case Uid:
|
||||||
|
return "Uid"
|
||||||
|
case AND:
|
||||||
|
return "AND"
|
||||||
|
case OR:
|
||||||
|
return "OR"
|
||||||
|
case NOT:
|
||||||
|
return "NOT"
|
||||||
default:
|
default:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
@ -58,7 +76,7 @@ type Rule interface {
|
|||||||
Adapter() string
|
Adapter() string
|
||||||
Payload() string
|
Payload() string
|
||||||
ShouldResolveIP() bool
|
ShouldResolveIP() bool
|
||||||
|
ShouldFindProcess() bool
|
||||||
RuleExtra() *RuleExtra
|
RuleExtra() *RuleExtra
|
||||||
SetRuleExtra(re *RuleExtra)
|
SetRuleExtra(re *RuleExtra)
|
||||||
ShouldFindProcess() bool
|
|
||||||
}
|
}
|
||||||
|
26
constant/sniffer.go
Normal file
26
constant/sniffer.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package constant
|
||||||
|
|
||||||
|
type Sniffer interface {
|
||||||
|
SupportNetwork() NetWork
|
||||||
|
SniffTCP(bytes []byte) (string, error)
|
||||||
|
Protocol() string
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
TLS SnifferType = iota
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
SnifferList = []SnifferType{TLS}
|
||||||
|
)
|
||||||
|
|
||||||
|
type SnifferType int
|
||||||
|
|
||||||
|
func (rt SnifferType) String() string {
|
||||||
|
switch rt {
|
||||||
|
case TLS:
|
||||||
|
return "TLS"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
127
constant/tun.go
127
constant/tun.go
@ -3,11 +3,7 @@ package constant
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"net/netip"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"golang.org/x/exp/slices"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var StackTypeMapping = map[string]TUNStack{
|
var StackTypeMapping = map[string]TUNStack{
|
||||||
@ -18,21 +14,10 @@ var StackTypeMapping = map[string]TUNStack{
|
|||||||
const (
|
const (
|
||||||
TunGvisor TUNStack = iota
|
TunGvisor TUNStack = iota
|
||||||
TunSystem
|
TunSystem
|
||||||
|
|
||||||
TunDisabled TUNState = iota
|
|
||||||
TunEnabled
|
|
||||||
TunPaused
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TUNStack int
|
type TUNStack int
|
||||||
|
|
||||||
type TUNState int
|
|
||||||
|
|
||||||
type TUNChangeCallback interface {
|
|
||||||
Pause()
|
|
||||||
Resume()
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalYAML unserialize TUNStack with yaml
|
// UnmarshalYAML unserialize TUNStack with yaml
|
||||||
func (e *TUNStack) UnmarshalYAML(unmarshal func(any) error) error {
|
func (e *TUNStack) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
var tp string
|
var tp string
|
||||||
@ -55,7 +40,7 @@ func (e TUNStack) MarshalYAML() (any, error) {
|
|||||||
// UnmarshalJSON unserialize TUNStack with json
|
// UnmarshalJSON unserialize TUNStack with json
|
||||||
func (e *TUNStack) UnmarshalJSON(data []byte) error {
|
func (e *TUNStack) UnmarshalJSON(data []byte) error {
|
||||||
var tp string
|
var tp string
|
||||||
_ = json.Unmarshal(data, &tp)
|
json.Unmarshal(data, &tp)
|
||||||
mode, exist := StackTypeMapping[strings.ToUpper(tp)]
|
mode, exist := StackTypeMapping[strings.ToUpper(tp)]
|
||||||
if !exist {
|
if !exist {
|
||||||
return errors.New("invalid tun stack")
|
return errors.New("invalid tun stack")
|
||||||
@ -79,113 +64,3 @@ func (e TUNStack) String() string {
|
|||||||
return "unknown"
|
return "unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type DNSAddrPort struct {
|
|
||||||
netip.AddrPort
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *DNSAddrPort) UnmarshalText(text []byte) error {
|
|
||||||
if len(text) == 0 {
|
|
||||||
*p = DNSAddrPort{}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
addrPort := string(text)
|
|
||||||
if strings.HasPrefix(addrPort, "any") {
|
|
||||||
_, port, _ := strings.Cut(addrPort, "any")
|
|
||||||
addrPort = "0.0.0.0" + port
|
|
||||||
}
|
|
||||||
|
|
||||||
ap, err := netip.ParseAddrPort(addrPort)
|
|
||||||
*p = DNSAddrPort{AddrPort: ap}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p DNSAddrPort) String() string {
|
|
||||||
addrPort := p.AddrPort.String()
|
|
||||||
if p.AddrPort.Addr().IsUnspecified() {
|
|
||||||
addrPort = "any:" + strconv.Itoa(int(p.AddrPort.Port()))
|
|
||||||
}
|
|
||||||
return addrPort
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSUrl struct {
|
|
||||||
Network string
|
|
||||||
AddrPort DNSAddrPort
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DNSUrl) UnmarshalYAML(unmarshal func(any) error) error {
|
|
||||||
var text string
|
|
||||||
if err := unmarshal(&text); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
text = strings.ToLower(text)
|
|
||||||
network := "udp"
|
|
||||||
if before, after, found := strings.Cut(text, "://"); found {
|
|
||||||
network = before
|
|
||||||
text = after
|
|
||||||
}
|
|
||||||
|
|
||||||
if network != "udp" && network != "tcp" {
|
|
||||||
return errors.New("invalid dns url schema")
|
|
||||||
}
|
|
||||||
|
|
||||||
ap := &DNSAddrPort{}
|
|
||||||
if err := ap.UnmarshalText([]byte(text)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
*d = DNSUrl{Network: network, AddrPort: *ap}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d DNSUrl) MarshalYAML() (any, error) {
|
|
||||||
return d.String(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DNSUrl) UnmarshalJSON(data []byte) error {
|
|
||||||
var text string
|
|
||||||
if err := json.Unmarshal(data, &text); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
text = strings.ToLower(text)
|
|
||||||
network := "udp"
|
|
||||||
if before, after, found := strings.Cut(text, "://"); found {
|
|
||||||
network = before
|
|
||||||
text = after
|
|
||||||
}
|
|
||||||
|
|
||||||
if network != "udp" && network != "tcp" {
|
|
||||||
return errors.New("invalid dns url schema")
|
|
||||||
}
|
|
||||||
|
|
||||||
ap := &DNSAddrPort{}
|
|
||||||
if err := ap.UnmarshalText([]byte(text)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
*d = DNSUrl{Network: network, AddrPort: *ap}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d DNSUrl) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(d.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d DNSUrl) String() string {
|
|
||||||
return d.Network + "://" + d.AddrPort.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func RemoveDuplicateDNSUrl(slice []DNSUrl) []DNSUrl {
|
|
||||||
slices.SortFunc[DNSUrl](slice, func(a, b DNSUrl) bool {
|
|
||||||
return a.Network < b.Network || (a.Network == b.Network && a.AddrPort.Addr().Less(b.AddrPort.Addr()))
|
|
||||||
})
|
|
||||||
|
|
||||||
return slices.CompactFunc[[]DNSUrl, DNSUrl](slice, func(a, b DNSUrl) bool {
|
|
||||||
return a.Network == b.Network && a.AddrPort == b.AddrPort
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Version = "unknown version"
|
Meta = true
|
||||||
|
Version = "1.10.0"
|
||||||
BuildTime = "unknown time"
|
BuildTime = "unknown time"
|
||||||
|
ClashName = "Clash.Meta"
|
||||||
)
|
)
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user