Compare commits
287 Commits
Author | SHA1 | Date | |
---|---|---|---|
c0a2473160 | |||
70a19b999d | |||
e54f51af81 | |||
b068466108 | |||
b562f28c1b | |||
230e01f078 | |||
082847b403 | |||
9471d80785 | |||
b263095533 | |||
14d5137703 | |||
d8a771916a | |||
f7f30d3406 | |||
b2c9cbb43e | |||
c733f80793 | |||
88d8f93793 | |||
e57a13ed7a | |||
23525ecc15 | |||
814bd05315 | |||
e81b88fb94 | |||
c4994d6429 | |||
0740d20ba0 | |||
9eaca6e4ab | |||
609869bf5a | |||
d68339cea7 | |||
0f4cdbf187 | |||
f3f8e7e52f | |||
8d07c1eb3e | |||
46edae9896 | |||
df0ab6aa8e | |||
7b48138ad0 | |||
e9032c55fa | |||
d75cb069d9 | |||
f69f635e0b | |||
8b5e511426 | |||
6641bf7c07 | |||
afc9f3f59a | |||
a55be58c01 | |||
dcf97ff5b4 | |||
72c0af9739 | |||
b0f9c6afa8 | |||
19bb0b655c | |||
26ce3e8814 | |||
aa207ec664 | |||
c626b988a6 | |||
82c387e92b | |||
14fb789002 | |||
9071351022 | |||
f688eda2c2 | |||
2810533df4 | |||
6b7144acce | |||
e68c0d088b | |||
2c0cc374d3 | |||
86d3d77a7f | |||
14a3ff32f6 | |||
50704eaeeb | |||
38458cc4d0 | |||
b19a49335f | |||
9dda932494 | |||
6ce7b6ef83 | |||
93ea037230 | |||
3f592988a9 | |||
96f490f84a | |||
37603735bd | |||
af40048841 | |||
3435c67e68 | |||
ecb9e4f57d | |||
dd61e8d19d | |||
eae06a4a7d | |||
0822b526d5 | |||
95e9ae2d8d | |||
29cf3ca0ef | |||
36716ca695 | |||
2334bafe68 | |||
bd4302e096 | |||
d8a1d88ded | |||
c427bc89ef | |||
4d7096f451 | |||
4525707048 | |||
b8267a69f6 | |||
ad53b42a68 | |||
93e0dbdc78 | |||
3e4bc9f85c | |||
8e10e67b89 | |||
3b0cc8548c | |||
e48ccdd4c8 | |||
e103040158 | |||
1948ea11ef | |||
6d375ac37e | |||
82a8c03953 | |||
207371aeae | |||
52cfa94652 | |||
65f4a35e7f | |||
e5284cf647 | |||
0a3595414e | |||
f4326daaa4 | |||
710cd5aed2 | |||
521a190b0f | |||
e22ff74e79 | |||
2c82a2bfc8 | |||
461e0a6873 | |||
d1fb442bd5 | |||
7c4a359a2b | |||
0cdc40beb3 | |||
4cd8b6f24f | |||
0f63682bdf | |||
52125a3992 | |||
06c9dfdb80 | |||
54386ccda3 | |||
d3c50cf89f | |||
50d2e082d5 | |||
c38469330d | |||
045c3a3ad4 | |||
904c354ee4 | |||
1a8a6d0b5d | |||
e0c8aed5c7 | |||
8f60d61ff9 | |||
5e6ab99403 | |||
8adcc4d83b | |||
b76737bdbb | |||
09f435d928 | |||
3dd9ea52d8 | |||
09917a2a95 | |||
96a4abf46c | |||
16e3090ee8 | |||
b3e10c05e6 | |||
112b3e5a6c | |||
60fdd82e2b | |||
9815010131 | |||
9875f8ea6e | |||
9e0bd62790 | |||
0d51877fcd | |||
e34090c39a | |||
5cc66e51db | |||
71f0a4e35e | |||
48a2013d9c | |||
6f3a654d6c | |||
0f7f0a9b1a | |||
d59e98dc83 | |||
b137a50d85 | |||
f75cd04181 | |||
b926f4cf09 | |||
5829c3d5be | |||
288afd1308 | |||
528fbd10e4 | |||
85128a634d | |||
f6acbaac7b | |||
b75da2c6d8 | |||
271ed2b9c1 | |||
1702e7ddb4 | |||
1fd8f690fe | |||
183e776970 | |||
f00dfdd34d | |||
0670275533 | |||
9e77c650d9 | |||
3497fdaf45 | |||
6077e825c5 | |||
0dd2a6dee5 | |||
c1b5e4f561 | |||
1a21c8ebfd | |||
f867f02546 | |||
7c6c147a18 | |||
0eff8516c0 | |||
34338e7107 | |||
57fdd223f1 | |||
bc3fc0c840 | |||
662038e40e | |||
53528f8275 | |||
1c792b46c9 | |||
2417cfda12 | |||
aa3516ca24 | |||
bcf5b21208 | |||
ba5eefb6dd | |||
407de7388c | |||
6adafde9a0 | |||
cba548114f | |||
016e7bd0b4 | |||
ad13ad8dba | |||
89168e6c96 | |||
a4b8e286db | |||
e837470a6a | |||
b589754485 | |||
0eccbb023c | |||
71a08ad8e2 | |||
0d4a999707 | |||
243d8a2844 | |||
225c530d13 | |||
cff4841f3e | |||
f352f4479e | |||
762f227512 | |||
936ea3aa55 | |||
cec2206774 | |||
90e3dccacd | |||
c92cda6980 | |||
49f8902961 | |||
7770e18430 | |||
593a63c228 | |||
744728cb84 | |||
2036f8cb7a | |||
531f487629 | |||
18f885a92a | |||
d3b280a7e5 | |||
d1f6886558 | |||
791d72e05b | |||
14600a8170 | |||
bb267e4a1f | |||
f99da37168 | |||
7a9d986ff3 | |||
63446da5fa | |||
acf55a7f64 | |||
8c608f5d7a | |||
7f0c7d7802 | |||
7683271fe6 | |||
23bb01a4df | |||
0011c7acfe | |||
d75f9ff783 | |||
815e80f720 | |||
ca5399a16e | |||
04927229ff | |||
c0bd82d62b | |||
5c8bb24121 | |||
575720e0cc | |||
e7997a035b | |||
287ad5bc53 | |||
c295c5e412 | |||
8636a4f589 | |||
7a0717830c | |||
5920b05752 | |||
26a87f9d34 | |||
8da19e81a4 | |||
1339487ce4 | |||
2383cca2ce | |||
53b5ef199f | |||
754df5ba9b | |||
1016355ef6 | |||
b594cbc68d | |||
42d33fe629 | |||
bfe51e46b0 | |||
e30a628702 | |||
5581698908 | |||
36b5d1f18f | |||
bd6c6a9ad1 | |||
83fac44010 | |||
15a77fa71b | |||
7768c5b933 | |||
4e91118a05 | |||
7b5e1f759c | |||
3f6c707aa9 | |||
532ec88964 | |||
cb118d4371 | |||
a7cfc81885 | |||
551ab68c1e | |||
ef6260282f | |||
49635eab6c | |||
a46041b81c | |||
a6bbc67afb | |||
afc4644dd1 | |||
1607d3253f | |||
34c8655974 | |||
5e4b35e03a | |||
fa9077969c | |||
fcb1a7813a | |||
6f1bc3d65b | |||
2b93c9d4c9 | |||
f93d6aa294 | |||
f192d591c7 | |||
03c249ecb1 | |||
da5db36ccf | |||
ca6e67a384 | |||
6636db242b | |||
f5715c4f42 | |||
9cfd26d440 | |||
dc24dd4d89 | |||
a64cea5011 | |||
f6743d4d21 | |||
970643b144 | |||
05bf4d44ab | |||
c7a349e1fe | |||
01a477bd3d | |||
91e35f2f6a | |||
b0e062dc7c | |||
09cd34ec07 | |||
da391356dd | |||
502aa61c0e | |||
cc6d496143 | |||
10e0231bc1 | |||
fd63707399 | |||
c5757a9b11 |
96
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
96
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: "[Bug]"
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- The English version is available. -->
|
||||||
|
感谢你向 Clash Core 提交 issue!
|
||||||
|
在提交之前,请确认:
|
||||||
|
|
||||||
|
- [ ] 我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
||||||
|
- [ ] 这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 Openclash、Koolclash 等)的特定问题
|
||||||
|
- [ ] 我已经使用 Clash core 的 dev 分支版本测试过,问题依旧存在
|
||||||
|
- [ ] 如果你可以自己 debug 并解决的话,提交 PR 吧!
|
||||||
|
|
||||||
|
请注意,如果你并没有遵照这个 issue template 填写内容,我们将直接关闭这个 issue。
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Thanks for submitting an issue towards the Clash core!
|
||||||
|
But before so, please do the following checklist:
|
||||||
|
|
||||||
|
- [ ] Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
||||||
|
- [ ] Your issue may already be reported! Please search on the [issue tracker](……/) before creating one.
|
||||||
|
- [ ] I have tested using the dev branch, and the issue still exists.
|
||||||
|
- [ ] This is an issue related to the Clash core, not to the derivatives of Clash, like Openclash or Koolclash
|
||||||
|
|
||||||
|
Please understand that we close issues that fail to follow the issue template.
|
||||||
|
-->
|
||||||
|
|
||||||
|
我都确认过了,我要继续提交。
|
||||||
|
<!-- None of the above, create a bug report -->
|
||||||
|
------------------------------------------------------------------
|
||||||
|
|
||||||
|
请附上任何可以帮助我们解决这个问题的信息,如果我们收到的信息不足,我们将对这个 issue 加上 *Needs more information* 标记并在收到更多资讯之前关闭 issue。
|
||||||
|
<!-- Make sure to add **all the information needed to understand the bug** so that someone can help. If the info is missing we'll add the 'Needs more information' label and close the issue until there is enough information. -->
|
||||||
|
|
||||||
|
### clash core config
|
||||||
|
<!--
|
||||||
|
在下方附上 Clash core 脱敏后配置文件的内容
|
||||||
|
Paste the Clash core configuration below.
|
||||||
|
-->
|
||||||
|
```
|
||||||
|
……
|
||||||
|
```
|
||||||
|
|
||||||
|
### Clash log
|
||||||
|
<!--
|
||||||
|
在下方附上 Clash Core 的日志,log level 最好使用 DEBUG
|
||||||
|
Paste the Clash core log below with the log level set to `DEBUG`.
|
||||||
|
-->
|
||||||
|
```
|
||||||
|
……
|
||||||
|
```
|
||||||
|
|
||||||
|
### 环境 Environment
|
||||||
|
|
||||||
|
* Clash Core 的操作系统 (the OS that the Clash core is running on)
|
||||||
|
……
|
||||||
|
* 使用者的操作系统 (the OS running on the client)
|
||||||
|
……
|
||||||
|
* 网路环境或拓扑 (network conditions/topology)
|
||||||
|
……
|
||||||
|
* iptables,如果适用 (if applicable)
|
||||||
|
……
|
||||||
|
* ISP 有没有进行 DNS 污染 (is your ISP performing DNS pollution?)
|
||||||
|
……
|
||||||
|
* 其他
|
||||||
|
……
|
||||||
|
|
||||||
|
### 说明 Description
|
||||||
|
|
||||||
|
<!--
|
||||||
|
请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?
|
||||||
|
-->
|
||||||
|
|
||||||
|
### 重现问题的具体布骤 Steps to Reproduce
|
||||||
|
|
||||||
|
1. [First Step]
|
||||||
|
2. [Second Step]
|
||||||
|
3. ……
|
||||||
|
|
||||||
|
**我预期会发生……?**
|
||||||
|
<!-- **Expected behavior:** [What you expected to happen] -->
|
||||||
|
|
||||||
|
**实际上发生了什麽?**
|
||||||
|
<!-- **Actual behavior:** [What actually happened] -->
|
||||||
|
|
||||||
|
### 可能的解决方案 Possible Solution
|
||||||
|
<!-- 此项非必须,但是如果你有想法的话欢迎提出。 -->
|
||||||
|
<!-- Not obligatory, but suggest a fix/reason for the bug, -->
|
||||||
|
<!-- or ideas how to implement the addition or change -->
|
||||||
|
|
||||||
|
### 更多信息 More Information
|
78
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
78
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea for this project
|
||||||
|
title: "[Feature]"
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- The English version is available. -->
|
||||||
|
感谢你向 Clash Core 提交 Feature Request!
|
||||||
|
在提交之前,请确认:
|
||||||
|
|
||||||
|
- [ ] 我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
||||||
|
|
||||||
|
请注意,如果你并没有遵照这个 issue template 填写内容,我们将直接关闭这个 issue。
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Thanks for submitting a feature request towards the Clash core!
|
||||||
|
But before so, please do the following checklist:
|
||||||
|
|
||||||
|
- [ ] I have searched on the [issue tracker](……/) before creating the issue.
|
||||||
|
|
||||||
|
Please understand that we close issues that fail to follow the issue template.
|
||||||
|
-->
|
||||||
|
|
||||||
|
我都确认过了,我要继续提交。
|
||||||
|
<!-- None of the above, create a feature request -->
|
||||||
|
------------------------------------------------------------------
|
||||||
|
|
||||||
|
请附上任何可以帮助我们解决这个问题的信息,如果我们收到的信息不足,我们将对这个 issue 加上 *Needs more information* 标记并在收到更多资讯之前关闭 issue。
|
||||||
|
<!-- Make sure to add **all the information needed to understand the bug** so that someone can help. If the info is missing we'll add the 'Needs more information' label and close the issue until there is enough information. -->
|
||||||
|
|
||||||
|
### Clash core config
|
||||||
|
<!--
|
||||||
|
在下方附上 Clash Core 脱敏后的配置内容
|
||||||
|
Paste the Clash core configuration below.
|
||||||
|
-->
|
||||||
|
```
|
||||||
|
……
|
||||||
|
```
|
||||||
|
|
||||||
|
### Clash log
|
||||||
|
<!--
|
||||||
|
在下方附上 Clash Core 的日志,log level 请使用 DEBUG
|
||||||
|
Paste the Clash core log below with the log level set to `DEBUG`.
|
||||||
|
-->
|
||||||
|
```
|
||||||
|
……
|
||||||
|
```
|
||||||
|
|
||||||
|
### 环境 Environment
|
||||||
|
|
||||||
|
* Clash Core 的操作系统 (the OS that the Clash core is running on)
|
||||||
|
……
|
||||||
|
* 使用者的操作系统 (the OS running on the client)
|
||||||
|
……
|
||||||
|
* 网路环境或拓扑 (network conditions/topology)
|
||||||
|
……
|
||||||
|
* iptables,如果适用 (if applicable)
|
||||||
|
……
|
||||||
|
* ISP 有没有进行 DNS 污染 (is your ISP performing DNS pollution?)
|
||||||
|
……
|
||||||
|
* 其他
|
||||||
|
……
|
||||||
|
|
||||||
|
### 说明 Description
|
||||||
|
|
||||||
|
<!--
|
||||||
|
请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
||||||
|
-->
|
||||||
|
|
||||||
|
### 可能的解决方案 Possible Solution
|
||||||
|
<!-- 此项非必须,但是如果你有想法的话欢迎提出。 -->
|
||||||
|
<!-- Not obligatory, but suggest a fix/reason for the bug, -->
|
||||||
|
<!-- or ideas how to implement the addition or change -->
|
||||||
|
|
||||||
|
### 更多信息 More Information
|
44
.github/workflows/go.yml
vendored
Normal file
44
.github/workflows/go.yml
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
name: Go
|
||||||
|
on: [push, pull_request]
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v1
|
||||||
|
with:
|
||||||
|
go-version: 1.14.x
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v1
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
|
- name: Get dependencies and run test
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
NAME: clash
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j releases
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
||||||
|
prerelease: true
|
7
.gitignore
vendored
7
.gitignore
vendored
@ -4,6 +4,7 @@
|
|||||||
*.dll
|
*.dll
|
||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
|
bin/*
|
||||||
|
|
||||||
# Test binary, build with `go test -c`
|
# Test binary, build with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
@ -13,3 +14,9 @@
|
|||||||
|
|
||||||
# dep
|
# dep
|
||||||
vendor
|
vendor
|
||||||
|
|
||||||
|
# GoLand
|
||||||
|
.idea/*
|
||||||
|
|
||||||
|
# macOS file
|
||||||
|
.DS_Store
|
||||||
|
26
.travis.yml
26
.travis.yml
@ -1,26 +0,0 @@
|
|||||||
language: go
|
|
||||||
sudo: false
|
|
||||||
go:
|
|
||||||
- "1.11"
|
|
||||||
install:
|
|
||||||
- "go mod download"
|
|
||||||
env:
|
|
||||||
global:
|
|
||||||
- NAME=clash
|
|
||||||
- BINDIR=bin
|
|
||||||
- GO111MODULE=on
|
|
||||||
script:
|
|
||||||
- go test ./...
|
|
||||||
before_deploy: make -j releases
|
|
||||||
deploy:
|
|
||||||
provider: releases
|
|
||||||
prerelease: true
|
|
||||||
skip_cleanup: true
|
|
||||||
api_key:
|
|
||||||
secure: dp1tc1h0er7aaAZ1hY0Xk/cUKwB0ifsAjg6e0M/Ad5NC87oucP6ESNFkDu0e9rUS1yB826/VnVGzNE/Z5zdjXVzPft+g5v5oRxzI4BKLhf07t9s+x8Z+3sApTxdsC5BvcN9x+5yRbpDLQ3biDPxSFu86j7m2pkEWw6XYNZO3/5y+RZXX7zu+d4MzTLUaA2kWl7KQAP0tEJNuw9ACDhpkw7LYbU/8q3E76prOTeme5/AT6Gxj7XhKUNP27lazhhqBSWM14ybPANqojNLEfMFHN/Eu2phYO07MuLTd4zuOIuw9y65kgvTFcHRlORjwUhnviXyA69obQejjgDI1WDOtU4PqpFaSLrxWtKI6k5VNWHARYggDm/wKl0WG7F0Kgio1KiGGhDg2yrbseXr/zBNaDhBtTFh6XJffqqwmgby1PXB6PWwfvWXooJMaQiFZczLWeMBl8v6XbSN6jtMTh/PQlKai6BcDd4LM8GQ7VHpSeff4qXEU4Vpnadjgs8VDPOHng6/HV+wDs8q2LrlMbnxLWxbCjOMUB6w7YnSrwH9owzKSoUs/531I4tTCRQIgipJtTK2b881/8osVjdMGS1mDXhBWO+OM0LCAdORJz+kN4PIkXXvKLt6jX74k6z4M3swFaqqtlTduN2Yy/ErsjguQO1VZfHmcpNssmJXI5QB9sxA=
|
|
||||||
file: bin/*
|
|
||||||
file_glob: true
|
|
||||||
on:
|
|
||||||
repo: Dreamacro/clash
|
|
||||||
branch: master
|
|
||||||
tags: true
|
|
17
Dockerfile
17
Dockerfile
@ -1,23 +1,16 @@
|
|||||||
FROM golang:latest as builder
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
RUN wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz -O /tmp/GeoLite2-Country.tar.gz && \
|
|
||||||
tar zxvf /tmp/GeoLite2-Country.tar.gz -C /tmp && \
|
|
||||||
mv /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /Country.mmdb
|
|
||||||
|
|
||||||
|
RUN apk add --no-cache make git && \
|
||||||
|
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
||||||
WORKDIR /clash-src
|
WORKDIR /clash-src
|
||||||
|
|
||||||
COPY . /clash-src
|
COPY . /clash-src
|
||||||
|
|
||||||
RUN go mod download && \
|
RUN go mod download && \
|
||||||
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '-w -s' -o /clash
|
make linux-amd64 && \
|
||||||
|
mv ./bin/clash-linux-amd64 /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates
|
RUN apk add --no-cache ca-certificates
|
||||||
|
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
COPY --from=builder /clash /
|
COPY --from=builder /clash /
|
||||||
|
|
||||||
EXPOSE 7890 7891
|
|
||||||
|
|
||||||
ENTRYPOINT ["/clash"]
|
ENTRYPOINT ["/clash"]
|
||||||
|
20
Dockerfile.arm32v7
Normal file
20
Dockerfile.arm32v7
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
|
RUN apk add --no-cache make git && \
|
||||||
|
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb && \
|
||||||
|
wget -O /qemu-arm-static https://github.com/multiarch/qemu-user-static/releases/latest/download/qemu-arm-static && \
|
||||||
|
chmod +x /qemu-arm-static
|
||||||
|
|
||||||
|
WORKDIR /clash-src
|
||||||
|
COPY . /clash-src
|
||||||
|
RUN go mod download && \
|
||||||
|
make linux-armv7 && \
|
||||||
|
mv ./bin/clash-linux-armv7 /clash
|
||||||
|
|
||||||
|
FROM arm32v7/alpine:latest
|
||||||
|
|
||||||
|
COPY --from=builder /qemu-arm-static /usr/bin/
|
||||||
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
|
COPY --from=builder /clash /
|
||||||
|
RUN apk add --no-cache ca-certificates
|
||||||
|
ENTRYPOINT ["/clash"]
|
20
Dockerfile.arm64v8
Normal file
20
Dockerfile.arm64v8
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
|
RUN apk add --no-cache make git && \
|
||||||
|
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb && \
|
||||||
|
wget -O /qemu-aarch64-static https://github.com/multiarch/qemu-user-static/releases/latest/download/qemu-aarch64-static && \
|
||||||
|
chmod +x /qemu-aarch64-static
|
||||||
|
|
||||||
|
WORKDIR /clash-src
|
||||||
|
COPY . /clash-src
|
||||||
|
RUN go mod download && \
|
||||||
|
make linux-armv8 && \
|
||||||
|
mv ./bin/clash-linux-armv8 /clash
|
||||||
|
|
||||||
|
FROM arm64v8/alpine:latest
|
||||||
|
|
||||||
|
COPY --from=builder /qemu-aarch64-static /usr/bin/
|
||||||
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
|
COPY --from=builder /clash /
|
||||||
|
RUN apk add --no-cache ca-certificates
|
||||||
|
ENTRYPOINT ["/clash"]
|
687
LICENSE
687
LICENSE
@ -1,21 +1,674 @@
|
|||||||
MIT License
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (c) 2018 Dreamacro
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Preamble
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
The GNU General Public License is a free, copyleft license for
|
||||||
copies or substantial portions of the Software.
|
software and other kinds of works.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
The licenses for most software and other practical works are designed
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
to take away your freedom to share and change the works. By contrast,
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
share and change all versions of a program--to make sure it remains free
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
GNU General Public License for most of our software; it applies also to
|
||||||
SOFTWARE.
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
96
Makefile
96
Makefile
@ -1,23 +1,97 @@
|
|||||||
NAME=clash
|
NAME=clash
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
GOBUILD=CGO_ENABLED=0 go build -ldflags '-w -s'
|
VERSION=$(shell git describe --tags || echo "unknown version")
|
||||||
|
BUILDTIME=$(shell date -u)
|
||||||
|
GOBUILD=CGO_ENABLED=0 go build -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
|
-w -s'
|
||||||
|
|
||||||
all: linux macos win64
|
PLATFORM_LIST = \
|
||||||
|
darwin-amd64 \
|
||||||
|
linux-386 \
|
||||||
|
linux-amd64 \
|
||||||
|
linux-armv5 \
|
||||||
|
linux-armv6 \
|
||||||
|
linux-armv7 \
|
||||||
|
linux-armv8 \
|
||||||
|
linux-mips-softfloat \
|
||||||
|
linux-mips-hardfloat \
|
||||||
|
linux-mipsle-softfloat \
|
||||||
|
linux-mipsle-hardfloat \
|
||||||
|
linux-mips64 \
|
||||||
|
linux-mips64le \
|
||||||
|
freebsd-386 \
|
||||||
|
freebsd-amd64
|
||||||
|
|
||||||
linux:
|
WINDOWS_ARCH_LIST = \
|
||||||
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
windows-386 \
|
||||||
|
windows-amd64
|
||||||
|
|
||||||
macos:
|
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||||
|
|
||||||
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
win64:
|
linux-386:
|
||||||
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64:
|
||||||
|
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv5:
|
||||||
|
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv6:
|
||||||
|
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv7:
|
||||||
|
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv8:
|
||||||
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips-softfloat:
|
||||||
|
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips-hardfloat:
|
||||||
|
GOARCH=mips GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mipsle-softfloat:
|
||||||
|
GOARCH=mipsle GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mipsle-hardfloat:
|
||||||
|
GOARCH=mipsle GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips64:
|
||||||
|
GOARCH=mips64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips64le:
|
||||||
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-386:
|
||||||
|
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-amd64:
|
||||||
|
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
windows-386:
|
||||||
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
releases: linux macos win64
|
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
||||||
chmod +x $(BINDIR)/$(NAME)-*
|
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
||||||
gzip $(BINDIR)/$(NAME)-linux
|
|
||||||
gzip $(BINDIR)/$(NAME)-macos
|
|
||||||
zip -m -j $(BINDIR)/$(NAME)-win64.zip $(BINDIR)/$(NAME)-win64.exe
|
|
||||||
|
|
||||||
|
$(gz_releases): %.gz : %
|
||||||
|
chmod +x $(BINDIR)/$(NAME)-$(basename $@)
|
||||||
|
gzip -f -S -$(VERSION).gz $(BINDIR)/$(NAME)-$(basename $@)
|
||||||
|
|
||||||
|
$(zip_releases): %.zip : %
|
||||||
|
zip -m -j $(BINDIR)/$(NAME)-$(basename $@)-$(VERSION).zip $(BINDIR)/$(NAME)-$(basename $@).exe
|
||||||
|
|
||||||
|
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
||||||
|
|
||||||
|
releases: $(gz_releases) $(zip_releases)
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm $(BINDIR)/*
|
||||||
|
379
README.md
379
README.md
@ -1,19 +1,16 @@
|
|||||||
<h1 align="center">
|
<h1 align="center">
|
||||||
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
||||||
<br>
|
<br>Clash<br>
|
||||||
Clash
|
|
||||||
<br>
|
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h4 align="center">A rule based proxy in Go.</h4>
|
<h4 align="center">A rule-based tunnel in Go.</h4>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://travis-ci.org/Dreamacro/clash">
|
<a href="https://github.com/Dreamacro/clash/actions">
|
||||||
<img src="https://img.shields.io/travis/Dreamacro/clash.svg?style=flat-square"
|
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
||||||
alt="Travis-CI">
|
|
||||||
</a>
|
</a>
|
||||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Dreamacro/clash/releases">
|
<a href="https://github.com/Dreamacro/clash/releases">
|
||||||
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
||||||
@ -22,61 +19,60 @@
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- HTTP/HTTPS and SOCKS proxy
|
- Local HTTP/HTTPS/SOCKS server with/without authentication
|
||||||
- Surge like configuration
|
- VMess, Shadowsocks, Trojan (experimental), Snell protocol support for remote connections. UDP is supported.
|
||||||
- GeoIP rule support
|
- Built-in DNS server that aims to minimize DNS pollution attacks, supports DoH/DoT upstream. Fake IP is also supported.
|
||||||
- Support Vmess/Shadowsocks/Socks5
|
- Rules based off domains, GEOIP, IP CIDR or ports to forward packets to different nodes
|
||||||
- Support for Netfilter TCP redirect
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node based off latency
|
||||||
|
- Remote providers, allowing users to get node lists remotely instead of hardcoding in config
|
||||||
## Discussion
|
- Netfilter TCP redirecting. You can deploy Clash on your Internet gateway with `iptables`.
|
||||||
|
- Comprehensive HTTP API controller
|
||||||
[Telegram Group](https://t.me/clash_discuss)
|
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
You can build from source:
|
Clash requires Go >= 1.13. You can build it from source:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go get -u -v github.com/Dreamacro/clash
|
$ go get -u -v github.com/Dreamacro/clash
|
||||||
```
|
```
|
||||||
|
|
||||||
Pre-built binaries are available: [release](https://github.com/Dreamacro/clash/releases)
|
Pre-built binaries are available here: [release](https://github.com/Dreamacro/clash/releases)
|
||||||
|
Pre-built TUN mode binaries are available here: [TUN release](https://github.com/Dreamacro/clash/releases/tag/TUN). Source is not currently available.
|
||||||
|
|
||||||
Requires Go >= 1.10.
|
Check Clash version with:
|
||||||
|
|
||||||
## Daemon
|
|
||||||
|
|
||||||
Unfortunately, there is no native elegant way to implement golang's daemon.
|
|
||||||
|
|
||||||
So we can use third-party daemon tools like pm2, supervisor, and so on.
|
|
||||||
|
|
||||||
In the case of [pm2](https://github.com/Unitech/pm2), we can start the daemon this way:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pm2 start clash
|
$ clash -v
|
||||||
```
|
```
|
||||||
|
|
||||||
If you have Docker installed, you can run clash directly using `docker-compose`.
|
## Daemonize Clash
|
||||||
|
|
||||||
[Run clash in docker](https://github.com/Dreamacro/clash/wiki/Run-clash-in-docker)
|
Unfortunately, there is no native or elegant way to implement daemons on Golang. We recommend using third-party daemon management tools like PM2, Supervisor or the like to keep Clash running as a service.
|
||||||
|
|
||||||
|
In the case of [pm2](https://github.com/Unitech/pm2), start the daemon this way:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ pm2 start clash
|
||||||
|
```
|
||||||
|
|
||||||
|
If you have Docker installed, it's recommended to deploy Clash directly using `docker-compose`: [run Clash in Docker](https://github.com/Dreamacro/clash/wiki/Run-clash-in-docker)
|
||||||
|
|
||||||
## Config
|
## Config
|
||||||
|
|
||||||
**NOTE: after v0.8.0, clash using yaml as configuration file**
|
The default configuration directory is `$HOME/.config/clash`.
|
||||||
|
|
||||||
The default configuration directory is `$HOME/.config/clash`
|
The name of the configuration file is `config.yaml`.
|
||||||
|
|
||||||
The name of the configuration file is `config.yml`
|
If you want to use another directory, use `-d` to control the configuration directory.
|
||||||
|
|
||||||
If you want to use another directory, you can use `-d` to control the configuration directory
|
For example, you can use the current directory as the configuration directory:
|
||||||
|
|
||||||
For example, you can use the current directory as the configuration directory
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
clash -d .
|
$ clash -d .
|
||||||
```
|
```
|
||||||
|
|
||||||
Below is a simple demo configuration file:
|
<details>
|
||||||
|
<summary>This is an example configuration file (click to expand)</summary>
|
||||||
|
|
||||||
```yml
|
```yml
|
||||||
# port of HTTP
|
# port of HTTP
|
||||||
@ -85,75 +81,281 @@ port: 7890
|
|||||||
# port of SOCKS5
|
# port of SOCKS5
|
||||||
socks-port: 7891
|
socks-port: 7891
|
||||||
|
|
||||||
# redir proxy for Linux and macOS
|
# redir port for Linux and macOS
|
||||||
# redir-port: 7892
|
# redir-port: 7892
|
||||||
|
|
||||||
allow-lan: false
|
allow-lan: false
|
||||||
|
|
||||||
# Rule / Global/ Direct (default is Rule)
|
# Only applicable when setting allow-lan to true
|
||||||
|
# "*": bind all IP addresses
|
||||||
|
# 192.168.122.11: bind a single IPv4 address
|
||||||
|
# "[aaaa::a8aa:ff:fe09:57d8]": bind a single IPv6 address
|
||||||
|
# bind-address: "*"
|
||||||
|
|
||||||
|
# Rule / Global / Direct (default is Rule)
|
||||||
mode: Rule
|
mode: Rule
|
||||||
|
|
||||||
# set log level to stdout (default is info)
|
# set log level to stdout (default is info)
|
||||||
# info / warning / error / debug
|
# info / warning / error / debug / silent
|
||||||
log-level: info
|
log-level: info
|
||||||
|
|
||||||
# A RESTful API for clash
|
# RESTful API for clash
|
||||||
external-controller: 127.0.0.1:9090
|
external-controller: 127.0.0.1:9090
|
||||||
|
|
||||||
|
# you can put the static web resource (such as clash-dashboard) to a directory, and clash would serve in `${API}/ui`
|
||||||
|
# input is a relative path to the configuration directory or an absolute path
|
||||||
|
# external-ui: folder
|
||||||
|
|
||||||
# Secret for RESTful API (Optional)
|
# Secret for RESTful API (Optional)
|
||||||
# secret: ""
|
# secret: ""
|
||||||
|
|
||||||
Proxy:
|
# experimental feature
|
||||||
|
experimental:
|
||||||
|
ignore-resolve-fail: true # ignore dns resolve fail, default value is true
|
||||||
|
# interface-name: en0 # outbound interface name
|
||||||
|
|
||||||
# shadowsocks
|
# authentication of local SOCKS5/HTTP(S) server
|
||||||
# The types of cipher are consistent with go-shadowsocks2
|
# authentication:
|
||||||
# support AEAD_AES_128_GCM AEAD_AES_192_GCM AEAD_AES_256_GCM AEAD_CHACHA20_POLY1305 AES-128-CTR AES-192-CTR AES-256-CTR AES-128-CFB AES-192-CFB AES-256-CFB CHACHA20-IETF XCHACHA20
|
# - "user1:pass1"
|
||||||
# In addition to what go-shadowsocks2 supports, it also supports chacha20 rc4-md5 xchacha20-ietf-poly1305
|
# - "user2:pass2"
|
||||||
- { name: "ss1", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password" }
|
|
||||||
- { name: "ss2", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password", obfs: tls, obfs-host: bing.com }
|
|
||||||
|
|
||||||
# vmess
|
# # experimental hosts, support wildcard (e.g. *.clash.dev Even *.foo.*.example.com)
|
||||||
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
# # static domain has a higher priority than wildcard domain (foo.example.com > *.example.com)
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto }
|
# hosts:
|
||||||
# with tls
|
# '*.clash.dev': 127.0.0.1
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true }
|
# 'alpha.clash.dev': '::1'
|
||||||
# with tls and skip-cert-verify
|
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true, skip-cert-verify: true }
|
|
||||||
# with ws
|
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path }
|
|
||||||
# with ws + tls
|
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path, tls: true }
|
|
||||||
|
|
||||||
# socks5
|
# dns:
|
||||||
- { name: "socks", type: socks5, server: server, port: 443 }
|
# enable: true # set true to enable dns (default is false)
|
||||||
# with tls
|
# ipv6: false # default is false
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, tls: true }
|
# listen: 0.0.0.0:53
|
||||||
# with tls and skip-cert-verify
|
# # default-nameserver: # resolve dns nameserver host, should fill pure IP
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, tls: true, skip-cert-verify: true }
|
# # - 114.114.114.114
|
||||||
|
# # - 8.8.8.8
|
||||||
|
# enhanced-mode: redir-host # or fake-ip
|
||||||
|
# # fake-ip-range: 198.18.0.1/16 # if you don't know what it is, don't change it
|
||||||
|
# fake-ip-filter: # fake ip white domain list
|
||||||
|
# - '*.lan'
|
||||||
|
# - localhost.ptlogin2.qq.com
|
||||||
|
# nameserver:
|
||||||
|
# - 114.114.114.114
|
||||||
|
# - tls://dns.rubyfish.cn:853 # dns over tls
|
||||||
|
# - https://1.1.1.1/dns-query # dns over https
|
||||||
|
# fallback: # concurrent request with nameserver, fallback used when GEOIP country isn't CN
|
||||||
|
# - tcp://1.1.1.1
|
||||||
|
# fallback-filter:
|
||||||
|
# geoip: true # default
|
||||||
|
# ipcidr: # ips in these subnets will be considered polluted
|
||||||
|
# - 240.0.0.0/4
|
||||||
|
|
||||||
Proxy Group:
|
proxies:
|
||||||
# url-test select which proxy will be used by benchmarking speed to a URL.
|
# shadowsocks
|
||||||
- { name: "auto", type: url-test, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
|
# The supported ciphers(encrypt methods):
|
||||||
|
# aes-128-gcm aes-192-gcm aes-256-gcm
|
||||||
|
# aes-128-cfb aes-192-cfb aes-256-cfb
|
||||||
|
# aes-128-ctr aes-192-ctr aes-256-ctr
|
||||||
|
# rc4-md5 chacha20-ietf xchacha20
|
||||||
|
# chacha20-ietf-poly1305 xchacha20-ietf-poly1305
|
||||||
|
- name: "ss1"
|
||||||
|
type: ss
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
cipher: chacha20-ietf-poly1305
|
||||||
|
password: "password"
|
||||||
|
# udp: true
|
||||||
|
|
||||||
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
# old obfs configuration format remove after prerelease
|
||||||
- { name: "fallback-auto", type: fallback, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
|
- name: "ss2"
|
||||||
|
type: ss
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
cipher: chacha20-ietf-poly1305
|
||||||
|
password: "password"
|
||||||
|
plugin: obfs
|
||||||
|
plugin-opts:
|
||||||
|
mode: tls # or http
|
||||||
|
# host: bing.com
|
||||||
|
|
||||||
# select is used for selecting proxy or proxy group
|
- name: "ss3"
|
||||||
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
type: ss
|
||||||
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
|
server: server
|
||||||
|
port: 443
|
||||||
|
cipher: chacha20-ietf-poly1305
|
||||||
|
password: "password"
|
||||||
|
plugin: v2ray-plugin
|
||||||
|
plugin-opts:
|
||||||
|
mode: websocket # no QUIC now
|
||||||
|
# tls: true # wss
|
||||||
|
# skip-cert-verify: true
|
||||||
|
# host: bing.com
|
||||||
|
# path: "/"
|
||||||
|
# mux: true
|
||||||
|
# headers:
|
||||||
|
# custom: value
|
||||||
|
|
||||||
Rule:
|
# vmess
|
||||||
- DOMAIN-SUFFIX,google.com,Proxy
|
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
||||||
- DOMAIN-KEYWORD,google,Proxy
|
- name: "vmess"
|
||||||
- DOMAIN,google.com,Proxy
|
type: vmess
|
||||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
server: server
|
||||||
- IP-CIDR,127.0.0.0/8,DIRECT
|
port: 443
|
||||||
- GEOIP,CN,DIRECT
|
uuid: uuid
|
||||||
# note: there is two ","
|
alterId: 32
|
||||||
- FINAL,,Proxy
|
cipher: auto
|
||||||
|
# udp: true
|
||||||
|
# tls: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
# network: ws
|
||||||
|
# ws-path: /path
|
||||||
|
# ws-headers:
|
||||||
|
# Host: v2ray.com
|
||||||
|
|
||||||
|
# socks5
|
||||||
|
- name: "socks"
|
||||||
|
type: socks5
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
# username: username
|
||||||
|
# password: password
|
||||||
|
# tls: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
# udp: true
|
||||||
|
|
||||||
|
# http
|
||||||
|
- name: "http"
|
||||||
|
type: http
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
# username: username
|
||||||
|
# password: password
|
||||||
|
# tls: true # https
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
# snell
|
||||||
|
- name: "snell"
|
||||||
|
type: snell
|
||||||
|
server: server
|
||||||
|
port: 44046
|
||||||
|
psk: yourpsk
|
||||||
|
# obfs-opts:
|
||||||
|
# mode: http # or tls
|
||||||
|
# host: bing.com
|
||||||
|
|
||||||
|
# trojan
|
||||||
|
- name: "trojan"
|
||||||
|
type: trojan
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
password: yourpsk
|
||||||
|
# udp: true
|
||||||
|
# sni: example.com # aka server name
|
||||||
|
# alpn:
|
||||||
|
# - h2
|
||||||
|
# - http/1.1
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
proxy-groups:
|
||||||
|
# relay chains the proxies. proxies shall not contain a proxy-group. No UDP support.
|
||||||
|
# Traffic: clash <-> http <-> vmess <-> ss1 <-> ss2 <-> Internet
|
||||||
|
- name: "relay"
|
||||||
|
type: relay
|
||||||
|
proxies:
|
||||||
|
- http
|
||||||
|
- vmess
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
|
||||||
|
# url-test select which proxy will be used by benchmarking speed to a URL.
|
||||||
|
- name: "auto"
|
||||||
|
type: url-test
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- vmess1
|
||||||
|
url: 'http://www.gstatic.com/generate_204'
|
||||||
|
interval: 300
|
||||||
|
|
||||||
|
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
||||||
|
- name: "fallback-auto"
|
||||||
|
type: fallback
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- vmess1
|
||||||
|
url: 'http://www.gstatic.com/generate_204'
|
||||||
|
interval: 300
|
||||||
|
|
||||||
|
# load-balance: The request of the same eTLD will be dial on the same proxy.
|
||||||
|
- name: "load-balance"
|
||||||
|
type: load-balance
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- vmess1
|
||||||
|
url: 'http://www.gstatic.com/generate_204'
|
||||||
|
interval: 300
|
||||||
|
|
||||||
|
# select is used for selecting proxy or proxy group
|
||||||
|
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
||||||
|
- name: Proxy
|
||||||
|
type: select
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- vmess1
|
||||||
|
- auto
|
||||||
|
|
||||||
|
- name: UseProvider
|
||||||
|
type: select
|
||||||
|
use:
|
||||||
|
- provider1
|
||||||
|
proxies:
|
||||||
|
- Proxy
|
||||||
|
- DIRECT
|
||||||
|
|
||||||
|
proxy-providers:
|
||||||
|
provider1:
|
||||||
|
type: http
|
||||||
|
url: "url"
|
||||||
|
interval: 3600
|
||||||
|
path: ./hk.yaml
|
||||||
|
health-check:
|
||||||
|
enable: true
|
||||||
|
interval: 600
|
||||||
|
url: http://www.gstatic.com/generate_204
|
||||||
|
test:
|
||||||
|
type: file
|
||||||
|
path: /test.yaml
|
||||||
|
health-check:
|
||||||
|
enable: true
|
||||||
|
interval: 36000
|
||||||
|
url: http://www.gstatic.com/generate_204
|
||||||
|
|
||||||
|
rules:
|
||||||
|
- DOMAIN-SUFFIX,google.com,auto
|
||||||
|
- DOMAIN-KEYWORD,google,auto
|
||||||
|
- DOMAIN,google.com,auto
|
||||||
|
- DOMAIN-SUFFIX,ad.com,REJECT
|
||||||
|
# rename SOURCE-IP-CIDR and would remove after prerelease
|
||||||
|
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
||||||
|
# optional param "no-resolve" for IP rules (GEOIP IP-CIDR)
|
||||||
|
- IP-CIDR,127.0.0.0/8,DIRECT
|
||||||
|
- GEOIP,CN,DIRECT
|
||||||
|
- DST-PORT,80,DIRECT
|
||||||
|
- SRC-PORT,7777,DIRECT
|
||||||
|
# FINAL would remove after prerelease
|
||||||
|
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
||||||
|
- MATCH,auto
|
||||||
```
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
## Thanks
|
## Advanced
|
||||||
|
[Provider](https://github.com/Dreamacro/clash/wiki/Provider)
|
||||||
|
|
||||||
|
## Documentations
|
||||||
|
https://clash.gitbook.io/
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
|
|
||||||
@ -167,5 +369,6 @@ Rule:
|
|||||||
|
|
||||||
- [x] Complementing the necessary rule operators
|
- [x] Complementing the necessary rule operators
|
||||||
- [x] Redir proxy
|
- [x] Redir proxy
|
||||||
- [ ] UDP support
|
- [x] UDP support
|
||||||
- [ ] Connection manager
|
- [x] Connection manager
|
||||||
|
- [ ] Event API
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
@ -10,32 +10,28 @@ import (
|
|||||||
|
|
||||||
// HTTPAdapter is a adapter for HTTP connection
|
// HTTPAdapter is a adapter for HTTP connection
|
||||||
type HTTPAdapter struct {
|
type HTTPAdapter struct {
|
||||||
|
net.Conn
|
||||||
metadata *C.Metadata
|
metadata *C.Metadata
|
||||||
conn net.Conn
|
|
||||||
R *http.Request
|
R *http.Request
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close HTTP connection
|
|
||||||
func (h *HTTPAdapter) Close() {
|
|
||||||
h.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata return destination metadata
|
// Metadata return destination metadata
|
||||||
func (h *HTTPAdapter) Metadata() *C.Metadata {
|
func (h *HTTPAdapter) Metadata() *C.Metadata {
|
||||||
return h.metadata
|
return h.metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Conn return raw net.Conn of HTTP
|
|
||||||
func (h *HTTPAdapter) Conn() net.Conn {
|
|
||||||
return h.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewHTTP is HTTPAdapter generator
|
// NewHTTP is HTTPAdapter generator
|
||||||
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
||||||
|
metadata := parseHTTPAddr(request)
|
||||||
|
metadata.Type = C.HTTP
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
return &HTTPAdapter{
|
return &HTTPAdapter{
|
||||||
metadata: parseHTTPAddr(request),
|
metadata: metadata,
|
||||||
R: request,
|
R: request,
|
||||||
conn: conn,
|
Conn: conn,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,14 +1,22 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS is HTTPAdapter generator
|
// NewHTTPS is HTTPAdapter generator
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
||||||
|
metadata := parseHTTPAddr(request)
|
||||||
|
metadata.Type = C.HTTPCONNECT
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
return &SocketAdapter{
|
return &SocketAdapter{
|
||||||
metadata: parseHTTPAddr(request),
|
metadata: metadata,
|
||||||
conn: conn,
|
Conn: conn,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
33
adapters/inbound/packet.go
Normal file
33
adapters/inbound/packet.go
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
||||||
|
type PacketAdapter struct {
|
||||||
|
C.UDPPacket
|
||||||
|
metadata *C.Metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata returns destination metadata
|
||||||
|
func (s *PacketAdapter) Metadata() *C.Metadata {
|
||||||
|
return s.metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPacket is PacketAdapter generator
|
||||||
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.UDP
|
||||||
|
metadata.Type = source
|
||||||
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return &PacketAdapter{
|
||||||
|
UDPPacket: packet,
|
||||||
|
metadata: metadata,
|
||||||
|
}
|
||||||
|
}
|
@ -1,37 +1,35 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// SocketAdapter is a adapter for socks and redir connection
|
// SocketAdapter is a adapter for socks and redir connection
|
||||||
type SocketAdapter struct {
|
type SocketAdapter struct {
|
||||||
conn net.Conn
|
net.Conn
|
||||||
metadata *C.Metadata
|
metadata *C.Metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close socks and redir connection
|
|
||||||
func (s *SocketAdapter) Close() {
|
|
||||||
s.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata return destination metadata
|
// Metadata return destination metadata
|
||||||
func (s *SocketAdapter) Metadata() *C.Metadata {
|
func (s *SocketAdapter) Metadata() *C.Metadata {
|
||||||
return s.metadata
|
return s.metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Conn return raw net.Conn
|
|
||||||
func (s *SocketAdapter) Conn() net.Conn {
|
|
||||||
return s.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSocket is SocketAdapter generator
|
// NewSocket is SocketAdapter generator
|
||||||
func NewSocket(target socks.Addr, conn net.Conn) *SocketAdapter {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, netType C.NetWork) *SocketAdapter {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = netType
|
||||||
|
metadata.Type = source
|
||||||
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
|
||||||
return &SocketAdapter{
|
return &SocketAdapter{
|
||||||
conn: conn,
|
Conn: conn,
|
||||||
metadata: parseSocksAddr(target),
|
metadata: metadata,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,41 +1,34 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
var host, port string
|
metadata := &C.Metadata{
|
||||||
var ip net.IP
|
AddrType: int(target[0]),
|
||||||
|
}
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
host = string(target[2 : 2+target[1]])
|
metadata.Host = string(target[2 : 2+target[1]])
|
||||||
port = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
case socks5.AtypIPv4:
|
||||||
if err == nil {
|
ip := net.IP(target[1 : 1+net.IPv4len])
|
||||||
ip = ipAddr.IP
|
metadata.DstIP = ip
|
||||||
}
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
case socks.AtypIPv4:
|
case socks5.AtypIPv6:
|
||||||
ip = net.IP(target[1 : 1+net.IPv4len])
|
ip := net.IP(target[1 : 1+net.IPv6len])
|
||||||
port = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstIP = ip
|
||||||
case socks.AtypIPv6:
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
ip = net.IP(target[1 : 1+net.IPv6len])
|
|
||||||
port = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &C.Metadata{
|
return metadata
|
||||||
NetWork: C.TCP,
|
|
||||||
AddrType: int(target[0]),
|
|
||||||
Host: host,
|
|
||||||
IP: &ip,
|
|
||||||
Port: port,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseHTTPAddr(request *http.Request) *C.Metadata {
|
func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||||
@ -44,28 +37,35 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
if port == "" {
|
if port == "" {
|
||||||
port = "80"
|
port = "80"
|
||||||
}
|
}
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
|
||||||
var resolveIP *net.IP
|
|
||||||
if err == nil {
|
|
||||||
resolveIP = &ipAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
var addType int
|
metadata := &C.Metadata{
|
||||||
ip := net.ParseIP(host)
|
|
||||||
switch {
|
|
||||||
case ip == nil:
|
|
||||||
addType = socks.AtypDomainName
|
|
||||||
case ip.To4() == nil:
|
|
||||||
addType = socks.AtypIPv6
|
|
||||||
default:
|
|
||||||
addType = socks.AtypIPv4
|
|
||||||
}
|
|
||||||
|
|
||||||
return &C.Metadata{
|
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
AddrType: addType,
|
AddrType: C.AtypDomainName,
|
||||||
Host: host,
|
Host: host,
|
||||||
IP: resolveIP,
|
DstIP: nil,
|
||||||
Port: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
switch {
|
||||||
|
case ip.To4() == nil:
|
||||||
|
metadata.AddrType = C.AtypIPv6
|
||||||
|
default:
|
||||||
|
metadata.AddrType = C.AtypIPv4
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAddr(addr string) (net.IP, string, error) {
|
||||||
|
host, port, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
return ip, port, nil
|
||||||
}
|
}
|
||||||
|
223
adapters/outbound/base.go
Normal file
223
adapters/outbound/base.go
Normal file
@ -0,0 +1,223 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
defaultURLTestTimeout = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
type Base struct {
|
||||||
|
name string
|
||||||
|
addr string
|
||||||
|
tp C.AdapterType
|
||||||
|
udp bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Name() string {
|
||||||
|
return b.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Type() C.AdapterType {
|
||||||
|
return b.tp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
return c, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) SupportUDP() bool {
|
||||||
|
return b.udp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": b.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Addr() string {
|
||||||
|
return b.addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBase(name string, addr string, tp C.AdapterType, udp bool) *Base {
|
||||||
|
return &Base{name, addr, tp, udp}
|
||||||
|
}
|
||||||
|
|
||||||
|
type conn struct {
|
||||||
|
net.Conn
|
||||||
|
chain C.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) Chains() C.Chain {
|
||||||
|
return c.chain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
||||||
|
c.chain = append(c.chain, a.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
|
return &conn{c, []string{a.Name()}}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PacketConn interface {
|
||||||
|
net.PacketConn
|
||||||
|
WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type packetConn struct {
|
||||||
|
PacketConn
|
||||||
|
chain C.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) Chains() C.Chain {
|
||||||
|
return c.chain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
||||||
|
c.chain = append(c.chain, a.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPacketConn(pc PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
|
return &packetConn{pc, []string{a.Name()}}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Proxy struct {
|
||||||
|
C.ProxyAdapter
|
||||||
|
history *queue.Queue
|
||||||
|
alive bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) Alive() bool {
|
||||||
|
return p.alive
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
||||||
|
defer cancel()
|
||||||
|
return p.DialContext(ctx, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
||||||
|
if err != nil {
|
||||||
|
p.alive = false
|
||||||
|
}
|
||||||
|
return conn, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) DelayHistory() []C.DelayHistory {
|
||||||
|
queue := p.history.Copy()
|
||||||
|
histories := []C.DelayHistory{}
|
||||||
|
for _, item := range queue {
|
||||||
|
histories = append(histories, item.(C.DelayHistory))
|
||||||
|
}
|
||||||
|
return histories
|
||||||
|
}
|
||||||
|
|
||||||
|
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
||||||
|
func (p *Proxy) LastDelay() (delay uint16) {
|
||||||
|
var max uint16 = 0xffff
|
||||||
|
if !p.alive {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
last := p.history.Last()
|
||||||
|
if last == nil {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
history := last.(C.DelayHistory)
|
||||||
|
if history.Delay == 0 {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
return history.Delay
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||||
|
inner, err := p.ProxyAdapter.MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return inner, err
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping := map[string]interface{}{}
|
||||||
|
json.Unmarshal(inner, &mapping)
|
||||||
|
mapping["history"] = p.DelayHistory()
|
||||||
|
mapping["name"] = p.Name()
|
||||||
|
return json.Marshal(mapping)
|
||||||
|
}
|
||||||
|
|
||||||
|
// URLTest get the delay for the specified URL
|
||||||
|
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||||
|
defer func() {
|
||||||
|
p.alive = err == nil
|
||||||
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
|
if err == nil {
|
||||||
|
record.Delay = t
|
||||||
|
}
|
||||||
|
p.history.Put(record)
|
||||||
|
if p.history.Len() > 10 {
|
||||||
|
p.history.Pop()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
addr, err := urlToMetadata(url)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
instance, err := p.DialContext(ctx, &addr)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer instance.Close()
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodHead, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
Dial: func(string, string) (net.Conn, error) {
|
||||||
|
return instance, nil
|
||||||
|
},
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{
|
||||||
|
Transport: transport,
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
},
|
||||||
|
}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
|
return &Proxy{adapter, queue.New(10), true}
|
||||||
|
}
|
@ -1,45 +1,61 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DirectAdapter is a directly connected adapter
|
type Direct struct {
|
||||||
type DirectAdapter struct {
|
*Base
|
||||||
conn net.Conn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close is used to close connection
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
func (d *DirectAdapter) Close() {
|
address := net.JoinHostPort(metadata.Host, metadata.DstPort)
|
||||||
d.conn.Close()
|
if metadata.DstIP != nil {
|
||||||
}
|
address = net.JoinHostPort(metadata.DstIP.String(), metadata.DstPort)
|
||||||
|
}
|
||||||
|
|
||||||
// Conn is used to http request
|
c, err := dialer.DialContext(ctx, "tcp", address)
|
||||||
func (d *DirectAdapter) Conn() net.Conn {
|
|
||||||
return d.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type Direct struct{}
|
|
||||||
|
|
||||||
func (d *Direct) Name() string {
|
|
||||||
return "DIRECT"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Direct) Type() C.AdapterType {
|
|
||||||
return C.Direct
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Direct) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
c, err := net.DialTimeout("tcp", net.JoinHostPort(metadata.String(), metadata.Port), tcpTimeout)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return &DirectAdapter{conn: c}, nil
|
return NewConn(c, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Direct) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := dialer.ListenPacket("udp", "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&directPacketConn{pc}, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type directPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dp *directPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
return dp.WriteTo(p, metadata.UDPAddr())
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
return &Direct{}
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: "DIRECT",
|
||||||
|
tp: C.Direct,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,136 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type proxy struct {
|
|
||||||
RawProxy C.Proxy
|
|
||||||
Valid bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Fallback struct {
|
|
||||||
name string
|
|
||||||
proxies []*proxy
|
|
||||||
rawURL string
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type FallbackOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Name() string {
|
|
||||||
return f.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Type() C.AdapterType {
|
|
||||||
return C.Fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
|
||||||
_, proxy := f.findNextValidProxy(0)
|
|
||||||
if proxy != nil {
|
|
||||||
return proxy.RawProxy.Name()
|
|
||||||
}
|
|
||||||
return f.proxies[0].RawProxy.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
idx := 0
|
|
||||||
var proxy *proxy
|
|
||||||
for {
|
|
||||||
idx, proxy = f.findNextValidProxy(idx)
|
|
||||||
if proxy == nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
adapter, err = proxy.RawProxy.Generator(metadata)
|
|
||||||
if err != nil {
|
|
||||||
proxy.Valid = false
|
|
||||||
idx++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return f.proxies[0].RawProxy.Generator(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Close() {
|
|
||||||
f.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) loop() {
|
|
||||||
tick := time.NewTicker(f.interval)
|
|
||||||
go f.validTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go f.validTest()
|
|
||||||
case <-f.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) findNextValidProxy(start int) (int, *proxy) {
|
|
||||||
for i := start; i < len(f.proxies); i++ {
|
|
||||||
if f.proxies[i].Valid {
|
|
||||||
return i, f.proxies[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) validTest() {
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(f.proxies))
|
|
||||||
|
|
||||||
for _, p := range f.proxies {
|
|
||||||
go func(p *proxy) {
|
|
||||||
_, err := DelayTest(p.RawProxy, f.rawURL)
|
|
||||||
p.Valid = err == nil
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
|
||||||
_, err := urlToMetadata(option.URL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) < 1 {
|
|
||||||
return nil, errors.New("The number of proxies cannot be 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
warpperProxies := make([]*proxy, len(proxies))
|
|
||||||
for idx := range proxies {
|
|
||||||
warpperProxies[idx] = &proxy{
|
|
||||||
RawProxy: proxies[idx],
|
|
||||||
Valid: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Fallback := &Fallback{
|
|
||||||
name: option.Name,
|
|
||||||
proxies: warpperProxies,
|
|
||||||
rawURL: option.URL,
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
|
||||||
go Fallback.loop()
|
|
||||||
return Fallback, nil
|
|
||||||
}
|
|
134
adapters/outbound/http.go
Normal file
134
adapters/outbound/http.go
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Http struct {
|
||||||
|
*Base
|
||||||
|
user string
|
||||||
|
pass string
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type HttpOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
if h.tlsConfig != nil {
|
||||||
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
|
err := cc.Handshake()
|
||||||
|
c = cc
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.shakeHand(metadata, c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
c, err = h.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
|
addr := metadata.RemoteAddress()
|
||||||
|
req := &http.Request{
|
||||||
|
Method: http.MethodConnect,
|
||||||
|
URL: &url.URL{
|
||||||
|
Host: addr,
|
||||||
|
},
|
||||||
|
Host: addr,
|
||||||
|
Header: http.Header{
|
||||||
|
"Proxy-Connection": []string{"Keep-Alive"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.user != "" && h.pass != "" {
|
||||||
|
auth := h.user + ":" + h.pass
|
||||||
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := req.Write(rw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusOK {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusProxyAuthRequired {
|
||||||
|
return errors.New("HTTP need auth")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusMethodNotAllowed {
|
||||||
|
return errors.New("CONNECT method not allowed by proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= http.StatusInternalServerError {
|
||||||
|
return errors.New(resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHttp(option HttpOption) *Http {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ClientSessionCache: getClientSessionCache(),
|
||||||
|
ServerName: option.Server,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Http{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Http,
|
||||||
|
},
|
||||||
|
user: option.UserName,
|
||||||
|
pass: option.Password,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
71
adapters/outbound/parser.go
Normal file
71
adapters/outbound/parser.go
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
|
proxyType, existType := mapping["type"].(string)
|
||||||
|
if !existType {
|
||||||
|
return nil, fmt.Errorf("Missing type")
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxy C.ProxyAdapter
|
||||||
|
err := fmt.Errorf("Cannot parse")
|
||||||
|
switch proxyType {
|
||||||
|
case "ss":
|
||||||
|
ssOption := &ShadowSocksOption{}
|
||||||
|
err = decoder.Decode(mapping, ssOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewShadowSocks(*ssOption)
|
||||||
|
case "socks5":
|
||||||
|
socksOption := &Socks5Option{}
|
||||||
|
err = decoder.Decode(mapping, socksOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = NewSocks5(*socksOption)
|
||||||
|
case "http":
|
||||||
|
httpOption := &HttpOption{}
|
||||||
|
err = decoder.Decode(mapping, httpOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = NewHttp(*httpOption)
|
||||||
|
case "vmess":
|
||||||
|
vmessOption := &VmessOption{}
|
||||||
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewVmess(*vmessOption)
|
||||||
|
case "snell":
|
||||||
|
snellOption := &SnellOption{}
|
||||||
|
err = decoder.Decode(mapping, snellOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewSnell(*snellOption)
|
||||||
|
case "trojan":
|
||||||
|
trojanOption := &TrojanOption{}
|
||||||
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewTrojan(*trojanOption)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewProxy(proxy), nil
|
||||||
|
}
|
@ -1,6 +1,8 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
@ -8,42 +10,32 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RejectAdapter is a reject connected adapter
|
|
||||||
type RejectAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (r *RejectAdapter) Close() {}
|
|
||||||
|
|
||||||
// Conn is used to http request
|
|
||||||
func (r *RejectAdapter) Conn() net.Conn {
|
|
||||||
return r.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reject) Name() string {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return "REJECT"
|
return NewConn(&NopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reject) Type() C.AdapterType {
|
func (r *Reject) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
return C.Reject
|
return nil, errors.New("match reject rule")
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Reject) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
return &RejectAdapter{conn: &NopConn{}}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
return &Reject{}
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "REJECT",
|
||||||
|
tp: C.Reject,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type NopConn struct{}
|
type NopConn struct{}
|
||||||
|
|
||||||
func (rw *NopConn) Read(b []byte) (int, error) {
|
func (rw *NopConn) Read(b []byte) (int, error) {
|
||||||
return len(b), nil
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw *NopConn) Write(b []byte) (int, error) {
|
func (rw *NopConn) Write(b []byte) (int, error) {
|
||||||
|
@ -1,71 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"sort"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Selector struct {
|
|
||||||
name string
|
|
||||||
selected C.Proxy
|
|
||||||
proxies map[string]C.Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
type SelectorOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Name() string {
|
|
||||||
return s.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Type() C.AdapterType {
|
|
||||||
return C.Selector
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
return s.selected.Generator(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Now() string {
|
|
||||||
return s.selected.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) All() []string {
|
|
||||||
var all []string
|
|
||||||
for k := range s.proxies {
|
|
||||||
all = append(all, k)
|
|
||||||
}
|
|
||||||
sort.Strings(all)
|
|
||||||
return all
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
|
||||||
proxy, exist := s.proxies[name]
|
|
||||||
if !exist {
|
|
||||||
return errors.New("Proxy does not exist")
|
|
||||||
}
|
|
||||||
s.selected = proxy
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("Provide at least one proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
mapping := make(map[string]C.Proxy)
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
mapping[proxy.Name()] = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &Selector{
|
|
||||||
name: name,
|
|
||||||
proxies: mapping,
|
|
||||||
selected: proxies[0],
|
|
||||||
}
|
|
||||||
return s, nil
|
|
||||||
}
|
|
@ -1,116 +1,231 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/simple-obfs"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
v2rayObfs "github.com/Dreamacro/clash/component/v2ray-plugin"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ShadowsocksAdapter is a shadowsocks adapter
|
|
||||||
type ShadowsocksAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (ss *ShadowsocksAdapter) Close() {
|
|
||||||
ss.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowsocksAdapter) Conn() net.Conn {
|
|
||||||
return ss.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
server string
|
*Base
|
||||||
name string
|
cipher core.Cipher
|
||||||
obfs string
|
|
||||||
obfsHost string
|
// obfs
|
||||||
cipher core.Cipher
|
obfsMode string
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
v2rayOption *v2rayObfs.Option
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
|
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
||||||
|
|
||||||
|
// deprecated when bump to 1.0
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
ObfsHost string `proxy:"obfs-host,omitempty"`
|
ObfsHost string `proxy:"obfs-host,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *ShadowSocks) Name() string {
|
type simpleObfsOption struct {
|
||||||
return ss.name
|
Mode string `obfs:"mode"`
|
||||||
|
Host string `obfs:"host,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *ShadowSocks) Type() C.AdapterType {
|
type v2rayObfsOption struct {
|
||||||
return C.Shadowsocks
|
Mode string `obfs:"mode"`
|
||||||
|
Host string `obfs:"host,omitempty"`
|
||||||
|
Path string `obfs:"path,omitempty"`
|
||||||
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *ShadowSocks) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
|
switch ss.obfsMode {
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", ss.server)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
switch ss.obfs {
|
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsHost)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
case "http":
|
case "http":
|
||||||
_, port, _ := net.SplitHostPort(ss.server)
|
_, port, _ := net.SplitHostPort(ss.addr)
|
||||||
c = obfs.NewHTTPObfs(c, ss.obfsHost, port)
|
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||||
|
case "websocket":
|
||||||
|
var err error
|
||||||
|
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c = ss.cipher.StreamConn(c)
|
c = ss.cipher.StreamConn(c)
|
||||||
_, err = c.Write(serializesSocksAddr(metadata))
|
_, err := c.Write(serializesSocksAddr(metadata))
|
||||||
return &ShadowsocksAdapter{conn: c}, err
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
c, err = ss.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, ss), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := dialer.ListenPacket("udp", "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc = ss.cipher.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": ss.Type().String(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
server := fmt.Sprintf("%s:%d", option.Server, option.Port)
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
cipher := option.Cipher
|
cipher := option.Cipher
|
||||||
password := option.Password
|
password := option.Password
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
ciph, err := core.PickCipher(cipher, nil, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
obfs := option.Obfs
|
var v2rayOption *v2rayObfs.Option
|
||||||
obfsHost := "bing.com"
|
var obfsOption *simpleObfsOption
|
||||||
if option.ObfsHost != "" {
|
obfsMode := ""
|
||||||
obfsHost = option.ObfsHost
|
|
||||||
|
// forward compatibility before 1.0
|
||||||
|
if option.Obfs != "" {
|
||||||
|
obfsMode = option.Obfs
|
||||||
|
obfsOption = &simpleObfsOption{
|
||||||
|
Host: "bing.com",
|
||||||
|
}
|
||||||
|
if option.ObfsHost != "" {
|
||||||
|
obfsOption.Host = option.ObfsHost
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
|
if option.Plugin == "obfs" {
|
||||||
|
opts := simpleObfsOption{Host: "bing.com"}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "tls" && opts.Mode != "http" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
|
}
|
||||||
|
obfsMode = opts.Mode
|
||||||
|
obfsOption = &opts
|
||||||
|
} else if option.Plugin == "v2ray-plugin" {
|
||||||
|
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "websocket" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
|
}
|
||||||
|
obfsMode = opts.Mode
|
||||||
|
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if opts.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
ServerName: opts.Host,
|
||||||
|
InsecureSkipVerify: opts.SkipCertVerify,
|
||||||
|
ClientSessionCache: getClientSessionCache(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v2rayOption = &v2rayObfs.Option{
|
||||||
|
Host: opts.Host,
|
||||||
|
Path: opts.Path,
|
||||||
|
Headers: opts.Headers,
|
||||||
|
TLSConfig: tlsConfig,
|
||||||
|
Mux: opts.Mux,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
server: server,
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
cipher: ciph,
|
addr: addr,
|
||||||
obfs: obfs,
|
tp: C.Shadowsocks,
|
||||||
obfsHost: obfsHost,
|
udp: option.UDP,
|
||||||
|
},
|
||||||
|
cipher: ciph,
|
||||||
|
|
||||||
|
obfsMode: obfsMode,
|
||||||
|
v2rayOption: v2rayOption,
|
||||||
|
obfsOption: obfsOption,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
type ssPacketConn struct {
|
||||||
var buf [][]byte
|
net.PacketConn
|
||||||
aType := uint8(metadata.AddrType)
|
rAddr net.Addr
|
||||||
p, _ := strconv.Atoi(metadata.Port)
|
}
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
|
||||||
switch metadata.AddrType {
|
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
case socks.AtypDomainName:
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
len := uint8(len(metadata.Host))
|
if err != nil {
|
||||||
host := []byte(metadata.Host)
|
return
|
||||||
buf = [][]byte{{aType, len}, host, port}
|
}
|
||||||
case socks.AtypIPv4:
|
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
host := metadata.IP.To4()
|
}
|
||||||
buf = [][]byte{{aType}, host, port}
|
|
||||||
case socks.AtypIPv6:
|
func (spc *ssPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
||||||
host := metadata.IP.To16()
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddr(metadata.RemoteAddress()), p)
|
||||||
buf = [][]byte{{aType}, host, port}
|
if err != nil {
|
||||||
}
|
return
|
||||||
return bytes.Join(buf, nil)
|
}
|
||||||
|
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := spc.PacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := socks5.SplitAddr(b[:n])
|
||||||
|
if addr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(b, b[len(addr):])
|
||||||
|
return n - len(addr), udpAddr, e
|
||||||
}
|
}
|
||||||
|
78
adapters/outbound/snell.go
Normal file
78
adapters/outbound/snell.go
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/component/snell"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Snell struct {
|
||||||
|
*Base
|
||||||
|
psk []byte
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnellOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Psk string `proxy:"psk"`
|
||||||
|
ObfsOpts map[string]interface{} `proxy:"obfs-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
switch s.obfsOption.Mode {
|
||||||
|
case "tls":
|
||||||
|
c = obfs.NewTLSObfs(c, s.obfsOption.Host)
|
||||||
|
case "http":
|
||||||
|
_, port, _ := net.SplitHostPort(s.addr)
|
||||||
|
c = obfs.NewHTTPObfs(c, s.obfsOption.Host, port)
|
||||||
|
}
|
||||||
|
c = snell.StreamConn(c, s.psk)
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
err := snell.WriteHeader(c, metadata.String(), uint(port))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
c, err = s.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
psk := []byte(option.Psk)
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
|
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
||||||
|
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
||||||
|
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if obfsOption.Mode != "tls" && obfsOption.Mode != "http" {
|
||||||
|
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Snell{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Snell,
|
||||||
|
},
|
||||||
|
psk: psk,
|
||||||
|
obfsOption: obfsOption,
|
||||||
|
}, nil
|
||||||
|
}
|
@ -1,112 +1,198 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
"net"
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Socks5Adapter is a shadowsocks adapter
|
|
||||||
type Socks5Adapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (ss *Socks5Adapter) Close() {
|
|
||||||
ss.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5Adapter) Conn() net.Conn {
|
|
||||||
return ss.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
addr string
|
*Base
|
||||||
name string
|
user string
|
||||||
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
skipCertVerify bool
|
skipCertVerify bool
|
||||||
|
tlsConfig *tls.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
type Socks5Option struct {
|
type Socks5Option struct {
|
||||||
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"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *Socks5) Name() string {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
return ss.name
|
if ss.tls {
|
||||||
}
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
|
err := cc.Handshake()
|
||||||
func (ss *Socks5) Type() C.AdapterType {
|
c = cc
|
||||||
return C.Socks5
|
if err != nil {
|
||||||
}
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
|
||||||
func (ss *Socks5) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
c, err := net.DialTimeout("tcp", ss.addr, tcpTimeout)
|
|
||||||
|
|
||||||
if err == nil && ss.tls {
|
|
||||||
tlsConfig := tls.Config{
|
|
||||||
InsecureSkipVerify: ss.skipCertVerify,
|
|
||||||
MaxVersion: tls.VersionTLS12,
|
|
||||||
}
|
}
|
||||||
c = tls.Client(c, &tlsConfig)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
var user *socks5.User
|
||||||
return nil, fmt.Errorf("%s connect error", ss.addr)
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
if err := ss.shakeHand(metadata, c); err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &Socks5Adapter{conn: c}, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
buf := make([]byte, socks.MaxAddrLen)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
|
||||||
// VER, CMD, RSV
|
|
||||||
_, err := rw.Write([]byte{5, 1, 0})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
c, err = ss.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
return NewConn(c, ss), nil
|
||||||
return err
|
}
|
||||||
|
|
||||||
|
func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
||||||
|
defer cancel()
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if buf[0] != 5 {
|
if ss.tls {
|
||||||
return errors.New("SOCKS version error")
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
} else if buf[1] != 0 {
|
err = cc.Handshake()
|
||||||
return errors.New("SOCKS need auth")
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
// VER, CMD, RSV, ADDR
|
defer func() {
|
||||||
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
|
if err != nil {
|
||||||
return err
|
c.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
var user *socks5.User
|
||||||
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
|
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
return err
|
if err != nil {
|
||||||
|
err = fmt.Errorf("client hanshake error: %w", err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
pc, err := dialer.ListenPacket("udp", "")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
io.Copy(ioutil.Discard, c)
|
||||||
|
c.Close()
|
||||||
|
// A UDP association terminates when the TCP connection that the UDP
|
||||||
|
// ASSOCIATE request arrived on terminates. RFC1928
|
||||||
|
pc.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindAddr.UDPAddr(), tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ClientSessionCache: getClientSessionCache(),
|
||||||
|
ServerName: option.Server,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &Socks5{
|
||||||
addr: fmt.Sprintf("%s:%d", option.Server, option.Port),
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Socks5,
|
||||||
|
udp: option.UDP,
|
||||||
|
},
|
||||||
|
user: option.UserName,
|
||||||
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
skipCertVerify: option.SkipCertVerify,
|
skipCertVerify: option.SkipCertVerify,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type socksPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
tcpConn net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddr(metadata.RemoteAddress()), p)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return uc.PacketConn.WriteTo(packet, uc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := uc.PacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
addr, payload, err := socks5.DecodeUDPPacket(b)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse udp addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// due to DecodeUDPPacket is mutable, record addr length
|
||||||
|
copy(b, payload)
|
||||||
|
return n - len(addr) - 3, udpAddr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksPacketConn) Close() error {
|
||||||
|
uc.tcpConn.Close()
|
||||||
|
return uc.PacketConn.Close()
|
||||||
|
}
|
||||||
|
116
adapters/outbound/trojan.go
Normal file
116
adapters/outbound/trojan.go
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/trojan"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Trojan struct {
|
||||||
|
*Base
|
||||||
|
instance *trojan.Trojan
|
||||||
|
}
|
||||||
|
|
||||||
|
type TrojanOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
c, err := t.instance.StreamConn(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = t.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
||||||
|
defer cancel()
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = t.instance.StreamConn(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(&trojanPacketConn{pc, c}, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": t.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
|
tOption := &trojan.Option{
|
||||||
|
Password: option.Password,
|
||||||
|
ALPN: option.ALPN,
|
||||||
|
ServerName: option.Server,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
ClientSessionCache: getClientSessionCache(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.SNI != "" {
|
||||||
|
tOption.ServerName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Trojan{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Trojan,
|
||||||
|
udp: option.UDP,
|
||||||
|
},
|
||||||
|
instance: trojan.New(tOption),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type trojanPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
conn net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tpc *trojanPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
||||||
|
return trojan.WritePacket(tpc.conn, serializesSocksAddr(metadata), p)
|
||||||
|
}
|
@ -1,126 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type URLTest struct {
|
|
||||||
name string
|
|
||||||
proxies []C.Proxy
|
|
||||||
rawURL string
|
|
||||||
fast C.Proxy
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
once int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type URLTestOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Name() string {
|
|
||||||
return u.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Type() C.AdapterType {
|
|
||||||
return C.URLTest
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
|
||||||
return u.fast.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
a, err := u.fast.Generator(metadata)
|
|
||||||
if err != nil {
|
|
||||||
go u.speedTest()
|
|
||||||
}
|
|
||||||
return a, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Close() {
|
|
||||||
u.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) loop() {
|
|
||||||
tick := time.NewTicker(u.interval)
|
|
||||||
go u.speedTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go u.speedTest()
|
|
||||||
case <-u.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) speedTest() {
|
|
||||||
if atomic.AddInt32(&u.once, 1) != 1 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer atomic.StoreInt32(&u.once, 0)
|
|
||||||
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(u.proxies))
|
|
||||||
c := make(chan interface{})
|
|
||||||
fast := selectFast(c)
|
|
||||||
timer := time.NewTimer(u.interval)
|
|
||||||
|
|
||||||
for _, p := range u.proxies {
|
|
||||||
go func(p C.Proxy) {
|
|
||||||
_, err := DelayTest(p, u.rawURL)
|
|
||||||
if err == nil {
|
|
||||||
c <- p
|
|
||||||
}
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
wg.Wait()
|
|
||||||
close(c)
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-timer.C:
|
|
||||||
// Wait for fast to return or close.
|
|
||||||
<-fast
|
|
||||||
case p, open := <-fast:
|
|
||||||
if open {
|
|
||||||
u.fast = p.(C.Proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
|
||||||
_, err := urlToMetadata(option.URL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(proxies) < 1 {
|
|
||||||
return nil, errors.New("The number of proxies cannot be 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
urlTest := &URLTest{
|
|
||||||
name: option.Name,
|
|
||||||
proxies: proxies[:],
|
|
||||||
rawURL: option.URL,
|
|
||||||
fast: proxies[0],
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
once: 0,
|
|
||||||
}
|
|
||||||
go urlTest.loop()
|
|
||||||
return urlTest, nil
|
|
||||||
}
|
|
@ -1,12 +1,17 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -14,38 +19,10 @@ const (
|
|||||||
tcpTimeout = 5 * time.Second
|
tcpTimeout = 5 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
// DelayTest get the delay for the specified URL
|
var (
|
||||||
func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
|
globalClientSessionCache tls.ClientSessionCache
|
||||||
addr, err := urlToMetadata(url)
|
once sync.Once
|
||||||
if err != nil {
|
)
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
|
||||||
instance, err := proxy.Generator(&addr)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer instance.Close()
|
|
||||||
transport := &http.Transport{
|
|
||||||
Dial: func(string, string) (net.Conn, error) {
|
|
||||||
return instance.Conn(), nil
|
|
||||||
},
|
|
||||||
// from http.DefaultTransport
|
|
||||||
MaxIdleConns: 100,
|
|
||||||
IdleConnTimeout: 90 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
}
|
|
||||||
client := http.Client{Transport: transport}
|
|
||||||
resp, err := client.Get(url)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resp.Body.Close()
|
|
||||||
t = int16(time.Since(start) / time.Millisecond)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
u, err := url.Parse(rawURL)
|
u, err := url.Parse(rawURL)
|
||||||
@ -55,11 +32,12 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
|
|
||||||
port := u.Port()
|
port := u.Port()
|
||||||
if port == "" {
|
if port == "" {
|
||||||
if u.Scheme == "https" {
|
switch u.Scheme {
|
||||||
|
case "https":
|
||||||
port = "443"
|
port = "443"
|
||||||
} else if u.Scheme == "http" {
|
case "http":
|
||||||
port = "80"
|
port = "80"
|
||||||
} else {
|
default:
|
||||||
err = fmt.Errorf("%s scheme not Support", rawURL)
|
err = fmt.Errorf("%s scheme not Support", rawURL)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -68,30 +46,55 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
AddrType: C.AtypDomainName,
|
||||||
Host: u.Hostname(),
|
Host: u.Hostname(),
|
||||||
IP: nil,
|
DstIP: nil,
|
||||||
Port: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func selectFast(in chan interface{}) chan interface{} {
|
|
||||||
out := make(chan interface{})
|
|
||||||
go func() {
|
|
||||||
p, open := <-in
|
|
||||||
if open {
|
|
||||||
out <- p
|
|
||||||
}
|
|
||||||
close(out)
|
|
||||||
for range in {
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
||||||
tcp.SetKeepAlivePeriod(30 * time.Second)
|
tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getClientSessionCache() tls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return globalClientSessionCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
|
var buf [][]byte
|
||||||
|
aType := uint8(metadata.AddrType)
|
||||||
|
p, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case socks5.AtypDomainName:
|
||||||
|
len := uint8(len(metadata.Host))
|
||||||
|
host := []byte(metadata.Host)
|
||||||
|
buf = [][]byte{{aType, len}, host, port}
|
||||||
|
case socks5.AtypIPv4:
|
||||||
|
host := metadata.DstIP.To4()
|
||||||
|
buf = [][]byte{{aType}, host, port}
|
||||||
|
case socks5.AtypIPv6:
|
||||||
|
host := metadata.DstIP.To16()
|
||||||
|
buf = [][]byte{{aType}, host, port}
|
||||||
|
}
|
||||||
|
return bytes.Join(buf, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := resolver.ResolveIP(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
@ -1,85 +1,104 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
"github.com/Dreamacro/clash/component/vmess"
|
"github.com/Dreamacro/clash/component/vmess"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// VmessAdapter is a vmess adapter
|
|
||||||
type VmessAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (v *VmessAdapter) Close() {
|
|
||||||
v.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *VmessAdapter) Conn() net.Conn {
|
|
||||||
return v.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
name string
|
*Base
|
||||||
server string
|
|
||||||
client *vmess.Client
|
client *vmess.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *Vmess) Name() string {
|
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
return ss.name
|
return v.client.New(c, parseVmessAddr(metadata))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *Vmess) Type() C.AdapterType {
|
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return C.Vmess
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Vmess) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error", ss.server)
|
return nil, fmt.Errorf("%s connect error", v.addr)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = ss.client.New(c, parseVmessAddr(metadata))
|
|
||||||
return &VmessAdapter{conn: c}, err
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
return NewConn(c, v), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vmess) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
// vmess use stream-oriented udp, so clash needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
||||||
|
defer cancel()
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error", v.addr)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = v.client.New(c, parseVmessAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
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: option.UUID,
|
||||||
AlterID: uint16(option.AlterID),
|
AlterID: uint16(option.AlterID),
|
||||||
Security: security,
|
Security: security,
|
||||||
TLS: option.TLS,
|
TLS: option.TLS,
|
||||||
Host: fmt.Sprintf("%s:%d", option.Server, option.Port),
|
HostName: option.Server,
|
||||||
NetWork: option.Network,
|
Port: strconv.Itoa(option.Port),
|
||||||
WebSocketPath: option.WSPath,
|
NetWork: option.Network,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
WebSocketPath: option.WSPath,
|
||||||
|
WebSocketHeaders: option.WSHeaders,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
SessionCache: getClientSessionCache(),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Vmess{
|
return &Vmess{
|
||||||
name: option.Name,
|
Base: &Base{
|
||||||
server: fmt.Sprintf("%s:%d", option.Server, option.Port),
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Vmess,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
client: client,
|
client: client,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@ -91,11 +110,11 @@ func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
|||||||
case C.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
addrType = byte(vmess.AtypIPv4)
|
addrType = byte(vmess.AtypIPv4)
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.IP.To4())
|
copy(addr[:], metadata.DstIP.To4())
|
||||||
case C.AtypIPv6:
|
case C.AtypIPv6:
|
||||||
addrType = byte(vmess.AtypIPv6)
|
addrType = byte(vmess.AtypIPv6)
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.IP.To16())
|
copy(addr[:], metadata.DstIP.To16())
|
||||||
case C.AtypDomainName:
|
case C.AtypDomainName:
|
||||||
addrType = byte(vmess.AtypDomainName)
|
addrType = byte(vmess.AtypDomainName)
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
@ -103,10 +122,29 @@ func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
|||||||
copy(addr[1:], []byte(metadata.Host))
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
}
|
}
|
||||||
|
|
||||||
port, _ := strconv.Atoi(metadata.Port)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
return &vmess.DstAddr{
|
return &vmess.DstAddr{
|
||||||
|
UDP: metadata.NetWork == C.UDP,
|
||||||
AddrType: addrType,
|
AddrType: addrType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Port: uint(port),
|
Port: uint(port),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type vmessPacketConn struct {
|
||||||
|
net.Conn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
return uc.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) WriteWithMetadata(p []byte, metadata *C.Metadata) (n int, err error) {
|
||||||
|
return uc.Conn.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, err := uc.Conn.Read(b)
|
||||||
|
return n, uc.rAddr, err
|
||||||
|
}
|
||||||
|
20
adapters/outboundgroup/common.go
Normal file
20
adapters/outboundgroup/common.go
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultGetProxiesDuration = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
func getProvidersProxies(providers []provider.ProxyProvider) []C.Proxy {
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for _, provider := range providers {
|
||||||
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
84
adapters/outboundgroup/fallback.go
Normal file
84
adapters/outboundgroup/fallback.go
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Fallback struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Now() string {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
return proxy.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
c, err := proxy.DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
pc, err := proxy.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) SupportUDP() bool {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
return proxy.SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range f.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": f.Type().String(),
|
||||||
|
"now": f.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := f.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(f.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) findAliveProxy() C.Proxy {
|
||||||
|
proxies := f.proxies()
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return f.proxies()[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFallback(name string, providers []provider.ProxyProvider) *Fallback {
|
||||||
|
return &Fallback{
|
||||||
|
Base: outbound.NewBase(name, "", C.Fallback, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
128
adapters/outboundgroup/loadbalance.go
Normal file
128
adapters/outboundgroup/loadbalance.go
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LoadBalance struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
maxRetry int
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func getKey(metadata *C.Metadata) string {
|
||||||
|
if metadata.Host != "" {
|
||||||
|
// ip host
|
||||||
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
|
return metadata.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
|
||||||
|
return etld
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if metadata.DstIP == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata.DstIP.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func jumpHash(key uint64, buckets int32) int32 {
|
||||||
|
var b, j int64
|
||||||
|
|
||||||
|
for j < int64(buckets) {
|
||||||
|
b = j
|
||||||
|
key = key*2862933555777941757 + 1
|
||||||
|
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return int32(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
|
proxies := lb.proxies()
|
||||||
|
buckets := int32(len(proxies))
|
||||||
|
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||||
|
idx := jumpHash(key, buckets)
|
||||||
|
proxy := proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
c, err = proxy.DialContext(ctx, metadata)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err = proxies[0].DialContext(ctx, metadata)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (pc C.PacketConn, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
|
proxies := lb.proxies()
|
||||||
|
buckets := int32(len(proxies))
|
||||||
|
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||||
|
idx := jumpHash(key, buckets)
|
||||||
|
proxy := proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy.DialUDP(metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0].DialUDP(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) SupportUDP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := lb.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(lb.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range lb.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": lb.Type().String(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoadBalance(name string, providers []provider.ProxyProvider) *LoadBalance {
|
||||||
|
return &LoadBalance{
|
||||||
|
Base: outbound.NewBase(name, "", C.LoadBalance, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
maxRetry: 3,
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
146
adapters/outboundgroup/parser.go
Normal file
146
adapters/outboundgroup/parser.go
Normal file
@ -0,0 +1,146 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errFormat = errors.New("format error")
|
||||||
|
errType = errors.New("unsupport type")
|
||||||
|
errMissUse = errors.New("`use` field should not be empty")
|
||||||
|
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||||
|
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
||||||
|
errDuplicateProvider = errors.New("`duplicate provider name")
|
||||||
|
)
|
||||||
|
|
||||||
|
type GroupCommonOption struct {
|
||||||
|
Name string `group:"name"`
|
||||||
|
Type string `group:"type"`
|
||||||
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
|
Use []string `group:"use,omitempty"`
|
||||||
|
URL string `group:"url,omitempty"`
|
||||||
|
Interval int `group:"interval,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy, providersMap map[string]provider.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
groupOption := &GroupCommonOption{}
|
||||||
|
if err := decoder.Decode(config, groupOption); err != nil {
|
||||||
|
return nil, errFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.Type == "" || groupOption.Name == "" {
|
||||||
|
return nil, errFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
groupName := groupOption.Name
|
||||||
|
|
||||||
|
providers := []provider.ProxyProvider{}
|
||||||
|
|
||||||
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
|
return nil, errMissProxy
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(groupOption.Proxies) != 0 {
|
||||||
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// if Use not empty, drop health check options
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0)
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
} else {
|
||||||
|
// select don't need health check
|
||||||
|
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0)
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
} else {
|
||||||
|
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||||
|
return nil, errMissHealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval))
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
providers = append(providers, list...)
|
||||||
|
}
|
||||||
|
|
||||||
|
var group C.ProxyAdapter
|
||||||
|
switch groupOption.Type {
|
||||||
|
case "url-test":
|
||||||
|
group = NewURLTest(groupName, providers)
|
||||||
|
case "select":
|
||||||
|
group = NewSelector(groupName, providers)
|
||||||
|
case "fallback":
|
||||||
|
group = NewFallback(groupName, providers)
|
||||||
|
case "load-balance":
|
||||||
|
group = NewLoadBalance(groupName, providers)
|
||||||
|
case "relay":
|
||||||
|
group = NewRelay(groupName, providers)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
return group, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
||||||
|
var ps []C.Proxy
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProviders(mapping map[string]provider.ProxyProvider, list []string) ([]provider.ProxyProvider, error) {
|
||||||
|
var ps []provider.ProxyProvider
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.VehicleType() == provider.Compatible {
|
||||||
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
84
adapters/outboundgroup/relay.go
Normal file
84
adapters/outboundgroup/relay.go
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Relay struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
proxies := r.proxies()
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("Proxy does not exist")
|
||||||
|
}
|
||||||
|
first := proxies[0]
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = last.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return outbound.NewConn(c, r), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range r.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": r.Type().String(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := r.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(r.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRelay(name string, providers []provider.ProxyProvider) *Relay {
|
||||||
|
return &Relay{
|
||||||
|
Base: outbound.NewBase(name, "", C.Relay, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
85
adapters/outboundgroup/selector.go
Normal file
85
adapters/outboundgroup/selector.go
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Selector struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
selected C.Proxy
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := s.selected.DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := s.selected.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) SupportUDP() bool {
|
||||||
|
return s.selected.SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range s.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": s.Type().String(),
|
||||||
|
"now": s.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Now() string {
|
||||||
|
return s.selected.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Set(name string) error {
|
||||||
|
for _, proxy := range s.proxies() {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
s.selected = proxy
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.New("Proxy does not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := s.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(s.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSelector(name string, providers []provider.ProxyProvider) *Selector {
|
||||||
|
selected := providers[0].Proxies()[0]
|
||||||
|
return &Selector{
|
||||||
|
Base: outbound.NewBase(name, "", C.Selector, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
selected: selected,
|
||||||
|
}
|
||||||
|
}
|
94
adapters/outboundgroup/urltest.go
Normal file
94
adapters/outboundgroup/urltest.go
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type URLTest struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
fastSingle *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Now() string {
|
||||||
|
return u.fast().Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
|
c, err = u.fast().DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
pc, err := u.fast().DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := u.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(u.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) fast() C.Proxy {
|
||||||
|
elm, _, _ := u.fastSingle.Do(func() (interface{}, error) {
|
||||||
|
proxies := u.proxies()
|
||||||
|
fast := proxies[0]
|
||||||
|
min := fast.LastDelay()
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
if !proxy.Alive() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delay := proxy.LastDelay()
|
||||||
|
if delay < min {
|
||||||
|
fast = proxy
|
||||||
|
min = delay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fast, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.(C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) SupportUDP() bool {
|
||||||
|
return u.fast().SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range u.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": u.Type().String(),
|
||||||
|
"now": u.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewURLTest(name string, providers []provider.ProxyProvider) *URLTest {
|
||||||
|
return &URLTest{
|
||||||
|
Base: outbound.NewBase(name, "", C.URLTest, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
fastSingle: singledo.NewSingle(time.Second * 10),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
53
adapters/outboundgroup/util.go
Normal file
53
adapters/outboundgroup/util.go
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
||||||
|
host, port, err := net.SplitHostPort(rawAddress)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("addrToMetadata failed: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
if ip.To4() != nil {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv4,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv6,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: host,
|
||||||
|
DstIP: nil,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
tcp.SetKeepAlive(true)
|
||||||
|
tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
70
adapters/provider/healthcheck.go
Normal file
70
adapters/provider/healthcheck.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultURLTestTimeout = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
type HealthCheckOption struct {
|
||||||
|
URL string
|
||||||
|
Interval uint
|
||||||
|
}
|
||||||
|
|
||||||
|
type HealthCheck struct {
|
||||||
|
url string
|
||||||
|
proxies []C.Proxy
|
||||||
|
interval uint
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) process() {
|
||||||
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
|
go hc.check()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
hc.check()
|
||||||
|
case <-hc.done:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
|
hc.proxies = proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) auto() bool {
|
||||||
|
return hc.interval != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) check() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
for _, proxy := range hc.proxies {
|
||||||
|
go proxy.URLTest(ctx, hc.url)
|
||||||
|
}
|
||||||
|
|
||||||
|
<-ctx.Done()
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) close() {
|
||||||
|
hc.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint) *HealthCheck {
|
||||||
|
return &HealthCheck{
|
||||||
|
proxies: proxies,
|
||||||
|
url: url,
|
||||||
|
interval: interval,
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
}
|
58
adapters/provider/parser.go
Normal file
58
adapters/provider/parser.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errVehicleType = errors.New("unsupport vehicle type")
|
||||||
|
)
|
||||||
|
|
||||||
|
type healthCheckSchema struct {
|
||||||
|
Enable bool `provider:"enable"`
|
||||||
|
URL string `provider:"url"`
|
||||||
|
Interval int `provider:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxyProviderSchema struct {
|
||||||
|
Type string `provider:"type"`
|
||||||
|
Path string `provider:"path"`
|
||||||
|
URL string `provider:"url,omitempty"`
|
||||||
|
Interval int `provider:"interval,omitempty"`
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseProxyProvider(name string, mapping map[string]interface{}) (ProxyProvider, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
schema := &proxyProviderSchema{}
|
||||||
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var hcInterval uint = 0
|
||||||
|
if schema.HealthCheck.Enable {
|
||||||
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
|
}
|
||||||
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval)
|
||||||
|
|
||||||
|
path := C.Path.Resolve(schema.Path)
|
||||||
|
|
||||||
|
var vehicle Vehicle
|
||||||
|
switch schema.Type {
|
||||||
|
case "file":
|
||||||
|
vehicle = NewFileVehicle(path)
|
||||||
|
case "http":
|
||||||
|
vehicle = NewHTTPVehicle(schema.URL, path)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
|
return NewProxySetProvider(name, interval, vehicle, hc), nil
|
||||||
|
}
|
333
adapters/provider/provider.go
Normal file
333
adapters/provider/provider.go
Normal file
@ -0,0 +1,333 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ReservedName = "default"
|
||||||
|
|
||||||
|
fileMode = 0666
|
||||||
|
)
|
||||||
|
|
||||||
|
// Provider Type
|
||||||
|
const (
|
||||||
|
Proxy ProviderType = iota
|
||||||
|
Rule
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProviderType defined
|
||||||
|
type ProviderType int
|
||||||
|
|
||||||
|
func (pt ProviderType) String() string {
|
||||||
|
switch pt {
|
||||||
|
case Proxy:
|
||||||
|
return "Proxy"
|
||||||
|
case Rule:
|
||||||
|
return "Rule"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provider interface
|
||||||
|
type Provider interface {
|
||||||
|
Name() string
|
||||||
|
VehicleType() VehicleType
|
||||||
|
Type() ProviderType
|
||||||
|
Initial() error
|
||||||
|
Reload() error
|
||||||
|
Destroy() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyProvider interface
|
||||||
|
type ProxyProvider interface {
|
||||||
|
Provider
|
||||||
|
Proxies() []C.Proxy
|
||||||
|
HealthCheck()
|
||||||
|
Update() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxySchema struct {
|
||||||
|
Proxies []map[string]interface{} `yaml:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxySetProvider struct {
|
||||||
|
name string
|
||||||
|
vehicle Vehicle
|
||||||
|
hash [16]byte
|
||||||
|
proxies []C.Proxy
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
ticker *time.Ticker
|
||||||
|
updatedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"name": pp.Name(),
|
||||||
|
"type": pp.Type().String(),
|
||||||
|
"vehicleType": pp.VehicleType().String(),
|
||||||
|
"proxies": pp.Proxies(),
|
||||||
|
"updatedAt": pp.updatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Name() string {
|
||||||
|
return pp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Reload() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) HealthCheck() {
|
||||||
|
pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Update() error {
|
||||||
|
return pp.pull()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Destroy() error {
|
||||||
|
pp.healthCheck.close()
|
||||||
|
|
||||||
|
if pp.ticker != nil {
|
||||||
|
pp.ticker.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Initial() error {
|
||||||
|
var buf []byte
|
||||||
|
var err error
|
||||||
|
var isLocal bool
|
||||||
|
if stat, err := os.Stat(pp.vehicle.Path()); err == nil {
|
||||||
|
buf, err = ioutil.ReadFile(pp.vehicle.Path())
|
||||||
|
modTime := stat.ModTime()
|
||||||
|
pp.updatedAt = &modTime
|
||||||
|
isLocal = true
|
||||||
|
} else {
|
||||||
|
buf, err = pp.vehicle.Read()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := pp.parse(buf)
|
||||||
|
if err != nil {
|
||||||
|
if !isLocal {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse local file error, fallback to remote
|
||||||
|
buf, err = pp.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err = pp.parse(buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pp.hash = md5.Sum(buf)
|
||||||
|
pp.setProxies(proxies)
|
||||||
|
|
||||||
|
// pull proxies automatically
|
||||||
|
if pp.ticker != nil {
|
||||||
|
go pp.pullLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) VehicleType() VehicleType {
|
||||||
|
return pp.vehicle.Type()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Type() ProviderType {
|
||||||
|
return Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Proxies() []C.Proxy {
|
||||||
|
return pp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) pullLoop() {
|
||||||
|
for range pp.ticker.C {
|
||||||
|
if err := pp.pull(); err != nil {
|
||||||
|
log.Warnln("[Provider] %s pull error: %s", pp.Name(), err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) pull() error {
|
||||||
|
buf, err := pp.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
hash := md5.Sum(buf)
|
||||||
|
if bytes.Equal(pp.hash[:], hash[:]) {
|
||||||
|
log.Debugln("[Provider] %s's proxies doesn't change", pp.Name())
|
||||||
|
pp.updatedAt = &now
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := pp.parse(buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Infoln("[Provider] %s's proxies update", pp.Name())
|
||||||
|
|
||||||
|
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pp.updatedAt = &now
|
||||||
|
pp.hash = hash
|
||||||
|
pp.setProxies(proxies)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) parse(buf []byte) ([]C.Proxy, error) {
|
||||||
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if schema.Proxies == nil {
|
||||||
|
return nil, errors.New("File must have a `proxies` field")
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for idx, mapping := range schema.Proxies {
|
||||||
|
proxy, err := outbound.ParseProxy(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("File doesn't have any valid proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
|
pp.proxies = proxies
|
||||||
|
pp.healthCheck.setProxy(proxies)
|
||||||
|
go pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxySetProvider(name string, interval time.Duration, vehicle Vehicle, hc *HealthCheck) *ProxySetProvider {
|
||||||
|
var ticker *time.Ticker
|
||||||
|
if interval != 0 {
|
||||||
|
ticker = time.NewTicker(interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ProxySetProvider{
|
||||||
|
name: name,
|
||||||
|
vehicle: vehicle,
|
||||||
|
proxies: []C.Proxy{},
|
||||||
|
healthCheck: hc,
|
||||||
|
ticker: ticker,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompatibleProvider struct {
|
||||||
|
name string
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
proxies []C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"name": cp.Name(),
|
||||||
|
"type": cp.Type().String(),
|
||||||
|
"vehicleType": cp.VehicleType().String(),
|
||||||
|
"proxies": cp.Proxies(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Name() string {
|
||||||
|
return cp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Reload() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Destroy() error {
|
||||||
|
cp.healthCheck.close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) HealthCheck() {
|
||||||
|
cp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Update() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Initial() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) VehicleType() VehicleType {
|
||||||
|
return Compatible
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Type() ProviderType {
|
||||||
|
return Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Proxies() []C.Proxy {
|
||||||
|
return cp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("Provider need one proxy at least")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
return &CompatibleProvider{
|
||||||
|
name: name,
|
||||||
|
proxies: proxies,
|
||||||
|
healthCheck: hc,
|
||||||
|
}, nil
|
||||||
|
}
|
109
adapters/provider/vehicle.go
Normal file
109
adapters/provider/vehicle.go
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Vehicle Type
|
||||||
|
const (
|
||||||
|
File VehicleType = iota
|
||||||
|
HTTP
|
||||||
|
Compatible
|
||||||
|
)
|
||||||
|
|
||||||
|
// VehicleType defined
|
||||||
|
type VehicleType int
|
||||||
|
|
||||||
|
func (v VehicleType) String() string {
|
||||||
|
switch v {
|
||||||
|
case File:
|
||||||
|
return "File"
|
||||||
|
case HTTP:
|
||||||
|
return "HTTP"
|
||||||
|
case Compatible:
|
||||||
|
return "Compatible"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Vehicle interface {
|
||||||
|
Read() ([]byte, error)
|
||||||
|
Path() string
|
||||||
|
Type() VehicleType
|
||||||
|
}
|
||||||
|
|
||||||
|
type FileVehicle struct {
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Type() VehicleType {
|
||||||
|
return File
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Path() string {
|
||||||
|
return f.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Read() ([]byte, error) {
|
||||||
|
return ioutil.ReadFile(f.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFileVehicle(path string) *FileVehicle {
|
||||||
|
return &FileVehicle{path: path}
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPVehicle struct {
|
||||||
|
url string
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Type() VehicleType {
|
||||||
|
return HTTP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Path() string {
|
||||||
|
return h.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, h.url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
DialContext: dialer.DialContext,
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{Transport: transport}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf, err := ioutil.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
||||||
|
return &HTTPVehicle{url, path}
|
||||||
|
}
|
106
common/cache/cache.go
vendored
Normal file
106
common/cache/cache.go
vendored
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cache store element with a expired time
|
||||||
|
type Cache struct {
|
||||||
|
*cache
|
||||||
|
}
|
||||||
|
|
||||||
|
type cache struct {
|
||||||
|
mapping sync.Map
|
||||||
|
janitor *janitor
|
||||||
|
}
|
||||||
|
|
||||||
|
type element struct {
|
||||||
|
Expired time.Time
|
||||||
|
Payload interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put element in Cache with its ttl
|
||||||
|
func (c *cache) Put(key interface{}, payload interface{}, ttl time.Duration) {
|
||||||
|
c.mapping.Store(key, &element{
|
||||||
|
Payload: payload,
|
||||||
|
Expired: time.Now().Add(ttl),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get element in Cache, and drop when it expired
|
||||||
|
func (c *cache) Get(key interface{}) interface{} {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
elm := item.(*element)
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return elm.Payload
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWithExpire element in Cache with Expire Time
|
||||||
|
func (c *cache) GetWithExpire(key interface{}) (payload interface{}, expired time.Time) {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
elm := item.(*element)
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return elm.Payload, elm.Expired
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cache) cleanup() {
|
||||||
|
c.mapping.Range(func(k, v interface{}) bool {
|
||||||
|
key := k.(string)
|
||||||
|
elm := v.(*element)
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type janitor struct {
|
||||||
|
interval time.Duration
|
||||||
|
stop chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *janitor) process(c *cache) {
|
||||||
|
ticker := time.NewTicker(j.interval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
c.cleanup()
|
||||||
|
case <-j.stop:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopJanitor(c *Cache) {
|
||||||
|
c.janitor.stop <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return *Cache
|
||||||
|
func New(interval time.Duration) *Cache {
|
||||||
|
j := &janitor{
|
||||||
|
interval: interval,
|
||||||
|
stop: make(chan struct{}),
|
||||||
|
}
|
||||||
|
c := &cache{janitor: j}
|
||||||
|
go j.process(c)
|
||||||
|
C := &Cache{c}
|
||||||
|
runtime.SetFinalizer(C, stopJanitor)
|
||||||
|
return C
|
||||||
|
}
|
70
common/cache/cache_test.go
vendored
Normal file
70
common/cache/cache_test.go
vendored
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCache_Basic(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("string", "a", ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
assert.Equal(t, i.(int), 1, "should recv 1")
|
||||||
|
|
||||||
|
s := c.Get("string")
|
||||||
|
assert.Equal(t, s.(string), "a", "should recv 'a'")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_TTL(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
now := time.Now()
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("int2", 2, ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
_, expired := c.GetWithExpire("int2")
|
||||||
|
assert.Equal(t, i.(int), 1, "should recv 1")
|
||||||
|
assert.True(t, now.Before(expired))
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i = c.Get("int")
|
||||||
|
j, _ := c.GetWithExpire("int2")
|
||||||
|
assert.Nil(t, i, "should recv nil")
|
||||||
|
assert.Nil(t, j, "should recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoCleanup(t *testing.T) {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i := c.Get("int")
|
||||||
|
j, _ := c.GetWithExpire("int")
|
||||||
|
assert.Nil(t, i, "should recv nil")
|
||||||
|
assert.Nil(t, j, "should recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoGC(t *testing.T) {
|
||||||
|
sign := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
sign <- struct{}{}
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-sign
|
||||||
|
runtime.GC()
|
||||||
|
}
|
171
common/cache/lrucache.go
vendored
Normal file
171
common/cache/lrucache.go
vendored
Normal file
@ -0,0 +1,171 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
// Modified by https://github.com/die-net/lrucache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"container/list"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Option is part of Functional Options Pattern
|
||||||
|
type Option func(*LruCache)
|
||||||
|
|
||||||
|
// EvictCallback is used to get a callback when a cache entry is evicted
|
||||||
|
type EvictCallback = func(key interface{}, value interface{})
|
||||||
|
|
||||||
|
// WithEvict set the evict callback
|
||||||
|
func WithEvict(cb EvictCallback) Option {
|
||||||
|
return func(l *LruCache) {
|
||||||
|
l.onEvict = cb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithUpdateAgeOnGet update expires when Get element
|
||||||
|
func WithUpdateAgeOnGet() Option {
|
||||||
|
return func(l *LruCache) {
|
||||||
|
l.updateAgeOnGet = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithAge defined element max age (second)
|
||||||
|
func WithAge(maxAge int64) Option {
|
||||||
|
return func(l *LruCache) {
|
||||||
|
l.maxAge = maxAge
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithSize defined max length of LruCache
|
||||||
|
func WithSize(maxSize int) Option {
|
||||||
|
return func(l *LruCache) {
|
||||||
|
l.maxSize = maxSize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LruCache is a thread-safe, in-memory lru-cache that evicts the
|
||||||
|
// least recently used entries from memory when (if set) the entries are
|
||||||
|
// older than maxAge (in seconds). Use the New constructor to create one.
|
||||||
|
type LruCache struct {
|
||||||
|
maxAge int64
|
||||||
|
maxSize int
|
||||||
|
mu sync.Mutex
|
||||||
|
cache map[interface{}]*list.Element
|
||||||
|
lru *list.List // Front is least-recent
|
||||||
|
updateAgeOnGet bool
|
||||||
|
onEvict EvictCallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLRUCache creates an LruCache
|
||||||
|
func NewLRUCache(options ...Option) *LruCache {
|
||||||
|
lc := &LruCache{
|
||||||
|
lru: list.New(),
|
||||||
|
cache: make(map[interface{}]*list.Element),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(lc)
|
||||||
|
}
|
||||||
|
|
||||||
|
return lc
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns the interface{} representation of a cached response and a bool
|
||||||
|
// set to true if the key was found.
|
||||||
|
func (c *LruCache) Get(key interface{}) (interface{}, bool) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
le, ok := c.cache[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.maxAge > 0 && le.Value.(*entry).expires <= time.Now().Unix() {
|
||||||
|
c.deleteElement(le)
|
||||||
|
c.maybeDeleteOldest()
|
||||||
|
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
c.lru.MoveToBack(le)
|
||||||
|
entry := le.Value.(*entry)
|
||||||
|
if c.maxAge > 0 && c.updateAgeOnGet {
|
||||||
|
entry.expires = time.Now().Unix() + c.maxAge
|
||||||
|
}
|
||||||
|
value := entry.value
|
||||||
|
|
||||||
|
return value, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exist returns if key exist in cache but not put item to the head of linked list
|
||||||
|
func (c *LruCache) Exist(key interface{}) bool {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
_, ok := c.cache[key]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set stores the interface{} representation of a response for a given key.
|
||||||
|
func (c *LruCache) Set(key interface{}, value interface{}) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
expires := int64(0)
|
||||||
|
if c.maxAge > 0 {
|
||||||
|
expires = time.Now().Unix() + c.maxAge
|
||||||
|
}
|
||||||
|
|
||||||
|
if le, ok := c.cache[key]; ok {
|
||||||
|
c.lru.MoveToBack(le)
|
||||||
|
e := le.Value.(*entry)
|
||||||
|
e.value = value
|
||||||
|
e.expires = expires
|
||||||
|
} else {
|
||||||
|
e := &entry{key: key, value: value, expires: expires}
|
||||||
|
c.cache[key] = c.lru.PushBack(e)
|
||||||
|
|
||||||
|
if c.maxSize > 0 {
|
||||||
|
if len := c.lru.Len(); len > c.maxSize {
|
||||||
|
c.deleteElement(c.lru.Front())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.maybeDeleteOldest()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes the value associated with a key.
|
||||||
|
func (c *LruCache) Delete(key string) {
|
||||||
|
c.mu.Lock()
|
||||||
|
|
||||||
|
if le, ok := c.cache[key]; ok {
|
||||||
|
c.deleteElement(le)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache) maybeDeleteOldest() {
|
||||||
|
if c.maxAge > 0 {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
for le := c.lru.Front(); le != nil && le.Value.(*entry).expires <= now; le = c.lru.Front() {
|
||||||
|
c.deleteElement(le)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *LruCache) deleteElement(le *list.Element) {
|
||||||
|
c.lru.Remove(le)
|
||||||
|
e := le.Value.(*entry)
|
||||||
|
delete(c.cache, e.key)
|
||||||
|
if c.onEvict != nil {
|
||||||
|
c.onEvict(e.key, e.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
key interface{}
|
||||||
|
value interface{}
|
||||||
|
expires int64
|
||||||
|
}
|
138
common/cache/lrucache_test.go
vendored
Normal file
138
common/cache/lrucache_test.go
vendored
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
var entries = []struct {
|
||||||
|
key string
|
||||||
|
value string
|
||||||
|
}{
|
||||||
|
{"1", "one"},
|
||||||
|
{"2", "two"},
|
||||||
|
{"3", "three"},
|
||||||
|
{"4", "four"},
|
||||||
|
{"5", "five"},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLRUCache(t *testing.T) {
|
||||||
|
c := NewLRUCache()
|
||||||
|
|
||||||
|
for _, e := range entries {
|
||||||
|
c.Set(e.key, e.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Delete("missing")
|
||||||
|
_, ok := c.Get("missing")
|
||||||
|
assert.False(t, ok)
|
||||||
|
|
||||||
|
for _, e := range entries {
|
||||||
|
value, ok := c.Get(e.key)
|
||||||
|
if assert.True(t, ok) {
|
||||||
|
assert.Equal(t, e.value, value.(string))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, e := range entries {
|
||||||
|
c.Delete(e.key)
|
||||||
|
|
||||||
|
_, ok := c.Get(e.key)
|
||||||
|
assert.False(t, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLRUMaxAge(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithAge(86400))
|
||||||
|
|
||||||
|
now := time.Now().Unix()
|
||||||
|
expected := now + 86400
|
||||||
|
|
||||||
|
// Add one expired entry
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
c.lru.Back().Value.(*entry).expires = now
|
||||||
|
|
||||||
|
// Reset
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
e := c.lru.Back().Value.(*entry)
|
||||||
|
assert.True(t, e.expires >= now)
|
||||||
|
c.lru.Back().Value.(*entry).expires = now
|
||||||
|
|
||||||
|
// Set a few and verify expiration times
|
||||||
|
for _, s := range entries {
|
||||||
|
c.Set(s.key, s.value)
|
||||||
|
e := c.lru.Back().Value.(*entry)
|
||||||
|
assert.True(t, e.expires >= expected && e.expires <= expected+10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure we can get them all
|
||||||
|
for _, s := range entries {
|
||||||
|
_, ok := c.Get(s.key)
|
||||||
|
assert.True(t, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expire all entries
|
||||||
|
for _, s := range entries {
|
||||||
|
le, ok := c.cache[s.key]
|
||||||
|
if assert.True(t, ok) {
|
||||||
|
le.Value.(*entry).expires = now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get one expired entry, which should clear all expired entries
|
||||||
|
_, ok := c.Get("3")
|
||||||
|
assert.False(t, ok)
|
||||||
|
assert.Equal(t, c.lru.Len(), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLRUpdateOnGet(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithAge(86400), WithUpdateAgeOnGet())
|
||||||
|
|
||||||
|
now := time.Now().Unix()
|
||||||
|
expires := now + 86400/2
|
||||||
|
|
||||||
|
// Add one expired entry
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
c.lru.Back().Value.(*entry).expires = expires
|
||||||
|
|
||||||
|
_, ok := c.Get("foo")
|
||||||
|
assert.True(t, ok)
|
||||||
|
assert.True(t, c.lru.Back().Value.(*entry).expires > expires)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMaxSize(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithSize(2))
|
||||||
|
// Add one expired entry
|
||||||
|
c.Set("foo", "bar")
|
||||||
|
_, ok := c.Get("foo")
|
||||||
|
assert.True(t, ok)
|
||||||
|
|
||||||
|
c.Set("bar", "foo")
|
||||||
|
c.Set("baz", "foo")
|
||||||
|
|
||||||
|
_, ok = c.Get("foo")
|
||||||
|
assert.False(t, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExist(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithSize(1))
|
||||||
|
c.Set(1, 2)
|
||||||
|
assert.True(t, c.Exist(1))
|
||||||
|
c.Set(2, 3)
|
||||||
|
assert.False(t, c.Exist(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEvict(t *testing.T) {
|
||||||
|
temp := 0
|
||||||
|
evict := func(key interface{}, value interface{}) {
|
||||||
|
temp = key.(int) + value.(int)
|
||||||
|
}
|
||||||
|
|
||||||
|
c := NewLRUCache(WithEvict(evict), WithSize(1))
|
||||||
|
c.Set(1, 2)
|
||||||
|
c.Set(2, 3)
|
||||||
|
|
||||||
|
assert.Equal(t, temp, 3)
|
||||||
|
}
|
50
common/murmur3/murmur.go
Normal file
50
common/murmur3/murmur.go
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package murmur3
|
||||||
|
|
||||||
|
type bmixer interface {
|
||||||
|
bmix(p []byte) (tail []byte)
|
||||||
|
Size() (n int)
|
||||||
|
reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
type digest struct {
|
||||||
|
clen int // Digested input cumulative length.
|
||||||
|
tail []byte // 0 to Size()-1 bytes view of `buf'.
|
||||||
|
buf [16]byte // Expected (but not required) to be Size() large.
|
||||||
|
seed uint32 // Seed for initializing the hash.
|
||||||
|
bmixer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *digest) BlockSize() int { return 1 }
|
||||||
|
|
||||||
|
func (d *digest) Write(p []byte) (n int, err error) {
|
||||||
|
n = len(p)
|
||||||
|
d.clen += n
|
||||||
|
|
||||||
|
if len(d.tail) > 0 {
|
||||||
|
// Stick back pending bytes.
|
||||||
|
nfree := d.Size() - len(d.tail) // nfree ∈ [1, d.Size()-1].
|
||||||
|
if nfree < len(p) {
|
||||||
|
// One full block can be formed.
|
||||||
|
block := append(d.tail, p[:nfree]...)
|
||||||
|
p = p[nfree:]
|
||||||
|
_ = d.bmix(block) // No tail.
|
||||||
|
} else {
|
||||||
|
// Tail's buf is large enough to prevent reallocs.
|
||||||
|
p = append(d.tail, p...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
d.tail = d.bmix(p)
|
||||||
|
|
||||||
|
// Keep own copy of the 0 to Size()-1 pending bytes.
|
||||||
|
nn := copy(d.buf[:], d.tail)
|
||||||
|
d.tail = d.buf[:nn]
|
||||||
|
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *digest) Reset() {
|
||||||
|
d.clen = 0
|
||||||
|
d.tail = nil
|
||||||
|
d.bmixer.reset()
|
||||||
|
}
|
145
common/murmur3/murmur32.go
Normal file
145
common/murmur3/murmur32.go
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
package murmur3
|
||||||
|
|
||||||
|
// https://github.com/spaolacci/murmur3/blob/master/murmur32.go
|
||||||
|
|
||||||
|
import (
|
||||||
|
"hash"
|
||||||
|
"math/bits"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Make sure interfaces are correctly implemented.
|
||||||
|
var (
|
||||||
|
_ hash.Hash32 = new(digest32)
|
||||||
|
_ bmixer = new(digest32)
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
c1_32 uint32 = 0xcc9e2d51
|
||||||
|
c2_32 uint32 = 0x1b873593
|
||||||
|
)
|
||||||
|
|
||||||
|
// digest32 represents a partial evaluation of a 32 bites hash.
|
||||||
|
type digest32 struct {
|
||||||
|
digest
|
||||||
|
h1 uint32 // Unfinalized running hash.
|
||||||
|
}
|
||||||
|
|
||||||
|
// New32 returns new 32-bit hasher
|
||||||
|
func New32() hash.Hash32 { return New32WithSeed(0) }
|
||||||
|
|
||||||
|
// New32WithSeed returns new 32-bit hasher set with explicit seed value
|
||||||
|
func New32WithSeed(seed uint32) hash.Hash32 {
|
||||||
|
d := new(digest32)
|
||||||
|
d.seed = seed
|
||||||
|
d.bmixer = d
|
||||||
|
d.Reset()
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *digest32) Size() int { return 4 }
|
||||||
|
|
||||||
|
func (d *digest32) reset() { d.h1 = d.seed }
|
||||||
|
|
||||||
|
func (d *digest32) Sum(b []byte) []byte {
|
||||||
|
h := d.Sum32()
|
||||||
|
return append(b, byte(h>>24), byte(h>>16), byte(h>>8), byte(h))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Digest as many blocks as possible.
|
||||||
|
func (d *digest32) bmix(p []byte) (tail []byte) {
|
||||||
|
h1 := d.h1
|
||||||
|
|
||||||
|
nblocks := len(p) / 4
|
||||||
|
for i := 0; i < nblocks; i++ {
|
||||||
|
k1 := *(*uint32)(unsafe.Pointer(&p[i*4]))
|
||||||
|
|
||||||
|
k1 *= c1_32
|
||||||
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
|
k1 *= c2_32
|
||||||
|
|
||||||
|
h1 ^= k1
|
||||||
|
h1 = bits.RotateLeft32(h1, 13)
|
||||||
|
h1 = h1*4 + h1 + 0xe6546b64
|
||||||
|
}
|
||||||
|
d.h1 = h1
|
||||||
|
return p[nblocks*d.Size():]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *digest32) Sum32() (h1 uint32) {
|
||||||
|
|
||||||
|
h1 = d.h1
|
||||||
|
|
||||||
|
var k1 uint32
|
||||||
|
switch len(d.tail) & 3 {
|
||||||
|
case 3:
|
||||||
|
k1 ^= uint32(d.tail[2]) << 16
|
||||||
|
fallthrough
|
||||||
|
case 2:
|
||||||
|
k1 ^= uint32(d.tail[1]) << 8
|
||||||
|
fallthrough
|
||||||
|
case 1:
|
||||||
|
k1 ^= uint32(d.tail[0])
|
||||||
|
k1 *= c1_32
|
||||||
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
|
k1 *= c2_32
|
||||||
|
h1 ^= k1
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 ^= uint32(d.clen)
|
||||||
|
|
||||||
|
h1 ^= h1 >> 16
|
||||||
|
h1 *= 0x85ebca6b
|
||||||
|
h1 ^= h1 >> 13
|
||||||
|
h1 *= 0xc2b2ae35
|
||||||
|
h1 ^= h1 >> 16
|
||||||
|
|
||||||
|
return h1
|
||||||
|
}
|
||||||
|
|
||||||
|
func Sum32(data []byte) uint32 { return Sum32WithSeed(data, 0) }
|
||||||
|
|
||||||
|
func Sum32WithSeed(data []byte, seed uint32) uint32 {
|
||||||
|
h1 := seed
|
||||||
|
|
||||||
|
nblocks := len(data) / 4
|
||||||
|
for i := 0; i < nblocks; i++ {
|
||||||
|
k1 := *(*uint32)(unsafe.Pointer(&data[i*4]))
|
||||||
|
|
||||||
|
k1 *= c1_32
|
||||||
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
|
k1 *= c2_32
|
||||||
|
|
||||||
|
h1 ^= k1
|
||||||
|
h1 = bits.RotateLeft32(h1, 13)
|
||||||
|
h1 = h1*4 + h1 + 0xe6546b64
|
||||||
|
}
|
||||||
|
|
||||||
|
tail := data[nblocks*4:]
|
||||||
|
|
||||||
|
var k1 uint32
|
||||||
|
switch len(tail) & 3 {
|
||||||
|
case 3:
|
||||||
|
k1 ^= uint32(tail[2]) << 16
|
||||||
|
fallthrough
|
||||||
|
case 2:
|
||||||
|
k1 ^= uint32(tail[1]) << 8
|
||||||
|
fallthrough
|
||||||
|
case 1:
|
||||||
|
k1 ^= uint32(tail[0])
|
||||||
|
k1 *= c1_32
|
||||||
|
k1 = bits.RotateLeft32(k1, 15)
|
||||||
|
k1 *= c2_32
|
||||||
|
h1 ^= k1
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 ^= uint32(len(data))
|
||||||
|
|
||||||
|
h1 ^= h1 >> 16
|
||||||
|
h1 *= 0x85ebca6b
|
||||||
|
h1 ^= h1 >> 13
|
||||||
|
h1 *= 0xc2b2ae35
|
||||||
|
h1 ^= h1 >> 16
|
||||||
|
|
||||||
|
return h1
|
||||||
|
}
|
@ -7,60 +7,58 @@ import (
|
|||||||
|
|
||||||
type Observable struct {
|
type Observable struct {
|
||||||
iterable Iterable
|
iterable Iterable
|
||||||
listener *sync.Map
|
listener map[Subscription]*Subscriber
|
||||||
|
mux sync.Mutex
|
||||||
done bool
|
done bool
|
||||||
doneLock sync.RWMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) process() {
|
func (o *Observable) process() {
|
||||||
for item := range o.iterable {
|
for item := range o.iterable {
|
||||||
o.listener.Range(func(key, value interface{}) bool {
|
o.mux.Lock()
|
||||||
elm := value.(*Subscriber)
|
for _, sub := range o.listener {
|
||||||
elm.Emit(item)
|
sub.Emit(item)
|
||||||
return true
|
}
|
||||||
})
|
o.mux.Unlock()
|
||||||
}
|
}
|
||||||
o.close()
|
o.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) close() {
|
func (o *Observable) close() {
|
||||||
o.doneLock.Lock()
|
o.mux.Lock()
|
||||||
o.done = true
|
defer o.mux.Unlock()
|
||||||
o.doneLock.Unlock()
|
|
||||||
|
|
||||||
o.listener.Range(func(key, value interface{}) bool {
|
o.done = true
|
||||||
elm := value.(*Subscriber)
|
for _, sub := range o.listener {
|
||||||
elm.Close()
|
sub.Close()
|
||||||
return true
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) Subscribe() (Subscription, error) {
|
func (o *Observable) Subscribe() (Subscription, error) {
|
||||||
o.doneLock.RLock()
|
o.mux.Lock()
|
||||||
done := o.done
|
defer o.mux.Unlock()
|
||||||
o.doneLock.RUnlock()
|
if o.done {
|
||||||
if done == true {
|
|
||||||
return nil, errors.New("Observable is closed")
|
return nil, errors.New("Observable is closed")
|
||||||
}
|
}
|
||||||
subscriber := newSubscriber()
|
subscriber := newSubscriber()
|
||||||
o.listener.Store(subscriber.Out(), subscriber)
|
o.listener[subscriber.Out()] = subscriber
|
||||||
return subscriber.Out(), nil
|
return subscriber.Out(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) UnSubscribe(sub Subscription) {
|
func (o *Observable) UnSubscribe(sub Subscription) {
|
||||||
elm, exist := o.listener.Load(sub)
|
o.mux.Lock()
|
||||||
|
defer o.mux.Unlock()
|
||||||
|
subscriber, exist := o.listener[sub]
|
||||||
if !exist {
|
if !exist {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
subscriber := elm.(*Subscriber)
|
delete(o.listener, sub)
|
||||||
o.listener.Delete(subscriber.Out())
|
|
||||||
subscriber.Close()
|
subscriber.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewObservable(any Iterable) *Observable {
|
func NewObservable(any Iterable) *Observable {
|
||||||
observable := &Observable{
|
observable := &Observable{
|
||||||
iterable: any,
|
iterable: any,
|
||||||
listener: &sync.Map{},
|
listener: map[Subscription]*Subscriber{},
|
||||||
}
|
}
|
||||||
go observable.process()
|
go observable.process()
|
||||||
return observable
|
return observable
|
||||||
|
@ -5,6 +5,8 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator(item []interface{}) chan interface{} {
|
func iterator(item []interface{}) chan interface{} {
|
||||||
@ -23,16 +25,12 @@ func TestObservable(t *testing.T) {
|
|||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
count := 0
|
count := 0
|
||||||
for range data {
|
for range data {
|
||||||
count = count + 1
|
count++
|
||||||
}
|
|
||||||
if count != 5 {
|
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
}
|
||||||
|
assert.Equal(t, count, 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_MutilSubscribe(t *testing.T) {
|
func TestObservable_MutilSubscribe(t *testing.T) {
|
||||||
@ -46,30 +44,24 @@ func TestObservable_MutilSubscribe(t *testing.T) {
|
|||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan interface{}) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count = count + 1
|
count++
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
go waitCh(ch1)
|
go waitCh(ch1)
|
||||||
go waitCh(ch2)
|
go waitCh(ch2)
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
if count != 10 {
|
assert.Equal(t, count, 10)
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribe(t *testing.T) {
|
func TestObservable_UnSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
src.UnSubscribe(data)
|
src.UnSubscribe(data)
|
||||||
_, open := <-data
|
_, open := <-data
|
||||||
if open {
|
assert.False(t, open)
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
||||||
@ -79,9 +71,7 @@ func TestObservable_SubscribeClosedSource(t *testing.T) {
|
|||||||
<-data
|
<-data
|
||||||
|
|
||||||
_, closed := src.Subscribe()
|
_, closed := src.Subscribe()
|
||||||
if closed == nil {
|
assert.NotNil(t, closed)
|
||||||
t.Error("Observable should be closed")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
||||||
@ -118,7 +108,5 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
}
|
}
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
now := runtime.NumGoroutine()
|
now := runtime.NumGoroutine()
|
||||||
if init != now {
|
assert.Equal(t, init, now)
|
||||||
t.Errorf("Goroutine Leak: init %d now %d", init, now)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
69
common/picker/picker.go
Normal file
69
common/picker/picker.go
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
package picker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Picker provides synchronization, and Context cancelation
|
||||||
|
// for groups of goroutines working on subtasks of a common task.
|
||||||
|
// Inspired by errGroup
|
||||||
|
type Picker struct {
|
||||||
|
ctx context.Context
|
||||||
|
cancel func()
|
||||||
|
|
||||||
|
wg sync.WaitGroup
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
result interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPicker(ctx context.Context, cancel func()) *Picker {
|
||||||
|
return &Picker{
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithContext returns a new Picker and an associated Context derived from ctx.
|
||||||
|
// and cancel when first element return.
|
||||||
|
func WithContext(ctx context.Context) (*Picker, context.Context) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
return newPicker(ctx, cancel), ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithTimeout returns a new Picker and an associated Context derived from ctx with timeout.
|
||||||
|
func WithTimeout(ctx context.Context, timeout time.Duration) (*Picker, context.Context) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
return newPicker(ctx, cancel), ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait blocks until all function calls from the Go method have returned,
|
||||||
|
// then returns the first nil error result (if any) from them.
|
||||||
|
func (p *Picker) Wait() interface{} {
|
||||||
|
p.wg.Wait()
|
||||||
|
if p.cancel != nil {
|
||||||
|
p.cancel()
|
||||||
|
}
|
||||||
|
return p.result
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go calls the given function in a new goroutine.
|
||||||
|
// The first call to return a nil error cancels the group; its result will be returned by Wait.
|
||||||
|
func (p *Picker) Go(f func() (interface{}, error)) {
|
||||||
|
p.wg.Add(1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
|
||||||
|
if ret, err := f(); err == nil {
|
||||||
|
p.once.Do(func() {
|
||||||
|
p.result = ret
|
||||||
|
if p.cancel != nil {
|
||||||
|
p.cancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
39
common/picker/picker_test.go
Normal file
39
common/picker/picker_test.go
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package picker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sleepAndSend(ctx context.Context, delay int, input interface{}) func() (interface{}, error) {
|
||||||
|
return func() (interface{}, error) {
|
||||||
|
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
||||||
|
select {
|
||||||
|
case <-timer.C:
|
||||||
|
return input, nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPicker_Basic(t *testing.T) {
|
||||||
|
picker, ctx := WithContext(context.Background())
|
||||||
|
picker.Go(sleepAndSend(ctx, 30, 2))
|
||||||
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
|
|
||||||
|
number := picker.Wait()
|
||||||
|
assert.NotNil(t, number)
|
||||||
|
assert.Equal(t, number.(int), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPicker_Timeout(t *testing.T) {
|
||||||
|
picker, ctx := WithTimeout(context.Background(), time.Millisecond*5)
|
||||||
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
|
|
||||||
|
number := picker.Wait()
|
||||||
|
assert.Nil(t, number)
|
||||||
|
}
|
15
common/pool/pool.go
Normal file
15
common/pool/pool.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// io.Copy default buffer size is 32 KiB
|
||||||
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
|
bufferSize = 20 * 1024
|
||||||
|
)
|
||||||
|
|
||||||
|
// BufPool provide buffer for relay
|
||||||
|
var BufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
|
71
common/queue/queue.go
Normal file
71
common/queue/queue.go
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
package queue
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Queue is a simple concurrent safe queue
|
||||||
|
type Queue struct {
|
||||||
|
items []interface{}
|
||||||
|
lock sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put add the item to the queue.
|
||||||
|
func (q *Queue) Put(items ...interface{}) {
|
||||||
|
if len(items) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
q.lock.Lock()
|
||||||
|
q.items = append(q.items, items...)
|
||||||
|
q.lock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pop returns the head of items.
|
||||||
|
func (q *Queue) Pop() interface{} {
|
||||||
|
if len(q.items) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
q.lock.Lock()
|
||||||
|
head := q.items[0]
|
||||||
|
q.items = q.items[1:]
|
||||||
|
q.lock.Unlock()
|
||||||
|
return head
|
||||||
|
}
|
||||||
|
|
||||||
|
// Last returns the last of item.
|
||||||
|
func (q *Queue) Last() interface{} {
|
||||||
|
if len(q.items) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
q.lock.RLock()
|
||||||
|
last := q.items[len(q.items)-1]
|
||||||
|
q.lock.RUnlock()
|
||||||
|
return last
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy get the copy of queue.
|
||||||
|
func (q *Queue) Copy() []interface{} {
|
||||||
|
items := []interface{}{}
|
||||||
|
q.lock.RLock()
|
||||||
|
items = append(items, q.items...)
|
||||||
|
q.lock.RUnlock()
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len returns the number of items in this queue.
|
||||||
|
func (q *Queue) Len() int64 {
|
||||||
|
q.lock.Lock()
|
||||||
|
defer q.lock.Unlock()
|
||||||
|
|
||||||
|
return int64(len(q.items))
|
||||||
|
}
|
||||||
|
|
||||||
|
// New is a constructor for a new concurrent safe queue.
|
||||||
|
func New(hint int64) *Queue {
|
||||||
|
return &Queue{
|
||||||
|
items: make([]interface{}, 0, hint),
|
||||||
|
}
|
||||||
|
}
|
55
common/singledo/singledo.go
Normal file
55
common/singledo/singledo.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package singledo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type call struct {
|
||||||
|
wg sync.WaitGroup
|
||||||
|
val interface{}
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Single struct {
|
||||||
|
mux sync.Mutex
|
||||||
|
last time.Time
|
||||||
|
wait time.Duration
|
||||||
|
call *call
|
||||||
|
result *Result
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Val interface{}
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
|
||||||
|
s.mux.Lock()
|
||||||
|
now := time.Now()
|
||||||
|
if now.Before(s.last.Add(s.wait)) {
|
||||||
|
s.mux.Unlock()
|
||||||
|
return s.result.Val, s.result.Err, true
|
||||||
|
}
|
||||||
|
|
||||||
|
if call := s.call; call != nil {
|
||||||
|
s.mux.Unlock()
|
||||||
|
call.wg.Wait()
|
||||||
|
return call.val, call.err, true
|
||||||
|
}
|
||||||
|
|
||||||
|
call := &call{}
|
||||||
|
call.wg.Add(1)
|
||||||
|
s.call = call
|
||||||
|
s.mux.Unlock()
|
||||||
|
call.val, call.err = fn()
|
||||||
|
call.wg.Done()
|
||||||
|
s.call = nil
|
||||||
|
s.result = &Result{call.val, call.err}
|
||||||
|
s.last = now
|
||||||
|
return call.val, call.err, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSingle(wait time.Duration) *Single {
|
||||||
|
return &Single{wait: wait}
|
||||||
|
}
|
53
common/singledo/singledo_test.go
Normal file
53
common/singledo/singledo_test.go
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
package singledo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBasic(t *testing.T) {
|
||||||
|
single := NewSingle(time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
shardCount := 0
|
||||||
|
call := func() (interface{}, error) {
|
||||||
|
foo++
|
||||||
|
time.Sleep(time.Millisecond * 5)
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
const n = 10
|
||||||
|
wg.Add(n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
go func() {
|
||||||
|
_, _, shard := single.Do(call)
|
||||||
|
if shard {
|
||||||
|
shardCount++
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
assert.Equal(t, 1, foo)
|
||||||
|
assert.Equal(t, 9, shardCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTimer(t *testing.T) {
|
||||||
|
single := NewSingle(time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
call := func() (interface{}, error) {
|
||||||
|
foo++
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
single.Do(call)
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
_, _, shard := single.Do(call)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, foo)
|
||||||
|
assert.True(t, shard)
|
||||||
|
}
|
@ -1,5 +1,7 @@
|
|||||||
package structure
|
package structure
|
||||||
|
|
||||||
|
// references: https://github.com/mitchellh/mapstructure
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
@ -45,11 +47,11 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok {
|
if !ok || value == nil {
|
||||||
if omitempty {
|
if omitempty {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
return fmt.Errorf("key %s missing", key)
|
return fmt.Errorf("key '%s' missing", key)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := d.decode(key, value, v.Field(idx))
|
err := d.decode(key, value, v.Field(idx))
|
||||||
@ -70,6 +72,12 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error
|
|||||||
return d.decodeBool(name, data, val)
|
return d.decodeBool(name, data, val)
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
return d.decodeSlice(name, data, val)
|
return d.decodeSlice(name, data, val)
|
||||||
|
case reflect.Map:
|
||||||
|
return d.decodeMap(name, data, val)
|
||||||
|
case reflect.Interface:
|
||||||
|
return d.setInterface(name, data, val)
|
||||||
|
case reflect.Struct:
|
||||||
|
return d.decodeStruct(name, data, val)
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("type %s not support", val.Kind().String())
|
return fmt.Errorf("type %s not support", val.Kind().String())
|
||||||
}
|
}
|
||||||
@ -108,7 +116,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value)
|
|||||||
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type'%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
name, val.Type(), dataVal.Type(),
|
name, val.Type(), dataVal.Type(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -125,7 +133,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (
|
|||||||
val.SetBool(dataVal.Int() != 0)
|
val.SetBool(dataVal.Int() != 0)
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type'%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
name, val.Type(), dataVal.Type(),
|
name, val.Type(), dataVal.Type(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -158,3 +166,234 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
|||||||
val.Set(valSlice)
|
val.Set(valSlice)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
|
||||||
|
valType := val.Type()
|
||||||
|
valKeyType := valType.Key()
|
||||||
|
valElemType := valType.Elem()
|
||||||
|
|
||||||
|
valMap := val
|
||||||
|
|
||||||
|
if valMap.IsNil() {
|
||||||
|
mapType := reflect.MapOf(valKeyType, valElemType)
|
||||||
|
valMap = reflect.MakeMap(mapType)
|
||||||
|
}
|
||||||
|
|
||||||
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
if dataVal.Kind() != reflect.Map {
|
||||||
|
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.decodeMapFromMap(name, dataVal, val, valMap)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
|
||||||
|
valType := val.Type()
|
||||||
|
valKeyType := valType.Key()
|
||||||
|
valElemType := valType.Elem()
|
||||||
|
|
||||||
|
errors := make([]string, 0)
|
||||||
|
|
||||||
|
if dataVal.Len() == 0 {
|
||||||
|
if dataVal.IsNil() {
|
||||||
|
if !val.IsNil() {
|
||||||
|
val.Set(dataVal)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val.Set(valMap)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, k := range dataVal.MapKeys() {
|
||||||
|
fieldName := fmt.Sprintf("%s[%s]", name, k)
|
||||||
|
|
||||||
|
currentKey := reflect.Indirect(reflect.New(valKeyType))
|
||||||
|
if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
v := dataVal.MapIndex(k).Interface()
|
||||||
|
if v == nil {
|
||||||
|
errors = append(errors, fmt.Sprintf("filed %s invalid", fieldName))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
currentVal := reflect.Indirect(reflect.New(valElemType))
|
||||||
|
if err := d.decode(fieldName, v, currentVal); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
valMap.SetMapIndex(currentKey, currentVal)
|
||||||
|
}
|
||||||
|
|
||||||
|
val.Set(valMap)
|
||||||
|
|
||||||
|
if len(errors) > 0 {
|
||||||
|
return fmt.Errorf(strings.Join(errors, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
|
||||||
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
|
||||||
|
// If the type of the value to write to and the data match directly,
|
||||||
|
// then we just set it directly instead of recursing into the structure.
|
||||||
|
if dataVal.Type() == val.Type() {
|
||||||
|
val.Set(dataVal)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
dataValKind := dataVal.Kind()
|
||||||
|
switch dataValKind {
|
||||||
|
case reflect.Map:
|
||||||
|
return d.decodeStructFromMap(name, dataVal, val)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error {
|
||||||
|
dataValType := dataVal.Type()
|
||||||
|
if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"'%s' needs a map with string keys, has '%s' keys",
|
||||||
|
name, dataValType.Key().Kind())
|
||||||
|
}
|
||||||
|
|
||||||
|
dataValKeys := make(map[reflect.Value]struct{})
|
||||||
|
dataValKeysUnused := make(map[interface{}]struct{})
|
||||||
|
for _, dataValKey := range dataVal.MapKeys() {
|
||||||
|
dataValKeys[dataValKey] = struct{}{}
|
||||||
|
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
errors := make([]string, 0)
|
||||||
|
|
||||||
|
// This slice will keep track of all the structs we'll be decoding.
|
||||||
|
// There can be more than one struct if there are embedded structs
|
||||||
|
// that are squashed.
|
||||||
|
structs := make([]reflect.Value, 1, 5)
|
||||||
|
structs[0] = val
|
||||||
|
|
||||||
|
// Compile the list of all the fields that we're going to be decoding
|
||||||
|
// from all the structs.
|
||||||
|
type field struct {
|
||||||
|
field reflect.StructField
|
||||||
|
val reflect.Value
|
||||||
|
}
|
||||||
|
fields := []field{}
|
||||||
|
for len(structs) > 0 {
|
||||||
|
structVal := structs[0]
|
||||||
|
structs = structs[1:]
|
||||||
|
|
||||||
|
structType := structVal.Type()
|
||||||
|
|
||||||
|
for i := 0; i < structType.NumField(); i++ {
|
||||||
|
fieldType := structType.Field(i)
|
||||||
|
fieldKind := fieldType.Type.Kind()
|
||||||
|
|
||||||
|
// If "squash" is specified in the tag, we squash the field down.
|
||||||
|
squash := false
|
||||||
|
tagParts := strings.Split(fieldType.Tag.Get(d.option.TagName), ",")
|
||||||
|
for _, tag := range tagParts[1:] {
|
||||||
|
if tag == "squash" {
|
||||||
|
squash = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if squash {
|
||||||
|
if fieldKind != reflect.Struct {
|
||||||
|
errors = append(errors,
|
||||||
|
fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind).Error())
|
||||||
|
} else {
|
||||||
|
structs = append(structs, structVal.FieldByName(fieldType.Name))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal struct field, store it away
|
||||||
|
fields = append(fields, field{fieldType, structVal.Field(i)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// for fieldType, field := range fields {
|
||||||
|
for _, f := range fields {
|
||||||
|
field, fieldValue := f.field, f.val
|
||||||
|
fieldName := field.Name
|
||||||
|
|
||||||
|
tagValue := field.Tag.Get(d.option.TagName)
|
||||||
|
tagValue = strings.SplitN(tagValue, ",", 2)[0]
|
||||||
|
if tagValue != "" {
|
||||||
|
fieldName = tagValue
|
||||||
|
}
|
||||||
|
|
||||||
|
rawMapKey := reflect.ValueOf(fieldName)
|
||||||
|
rawMapVal := dataVal.MapIndex(rawMapKey)
|
||||||
|
if !rawMapVal.IsValid() {
|
||||||
|
// Do a slower search by iterating over each key and
|
||||||
|
// doing case-insensitive search.
|
||||||
|
for dataValKey := range dataValKeys {
|
||||||
|
mK, ok := dataValKey.Interface().(string)
|
||||||
|
if !ok {
|
||||||
|
// Not a string key
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.EqualFold(mK, fieldName) {
|
||||||
|
rawMapKey = dataValKey
|
||||||
|
rawMapVal = dataVal.MapIndex(dataValKey)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !rawMapVal.IsValid() {
|
||||||
|
// There was no matching key in the map for the value in
|
||||||
|
// the struct. Just ignore.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the key we're using from the unused map so we stop tracking
|
||||||
|
delete(dataValKeysUnused, rawMapKey.Interface())
|
||||||
|
|
||||||
|
if !fieldValue.IsValid() {
|
||||||
|
// This should never happen
|
||||||
|
panic("field is not valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we can't set the field, then it is unexported or something,
|
||||||
|
// and we just continue onwards.
|
||||||
|
if !fieldValue.CanSet() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the name is empty string, then we're at the root, and we
|
||||||
|
// don't dot-join the fields.
|
||||||
|
if name != "" {
|
||||||
|
fieldName = fmt.Sprintf("%s.%s", name, fieldName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errors) > 0 {
|
||||||
|
return fmt.Errorf(strings.Join(errors, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) setInterface(name string, data interface{}, val reflect.Value) (err error) {
|
||||||
|
dataVal := reflect.ValueOf(data)
|
||||||
|
val.Set(dataVal)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
46
component/auth/auth.go
Normal file
46
component/auth/auth.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Authenticator interface {
|
||||||
|
Verify(user string, pass string) bool
|
||||||
|
Users() []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthUser struct {
|
||||||
|
User string
|
||||||
|
Pass string
|
||||||
|
}
|
||||||
|
|
||||||
|
type inMemoryAuthenticator struct {
|
||||||
|
storage *sync.Map
|
||||||
|
usernames []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (au *inMemoryAuthenticator) Verify(user string, pass string) bool {
|
||||||
|
realPass, ok := au.storage.Load(user)
|
||||||
|
return ok && realPass == pass
|
||||||
|
}
|
||||||
|
|
||||||
|
func (au *inMemoryAuthenticator) Users() []string { return au.usernames }
|
||||||
|
|
||||||
|
func NewAuthenticator(users []AuthUser) Authenticator {
|
||||||
|
if len(users) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
au := &inMemoryAuthenticator{storage: &sync.Map{}}
|
||||||
|
for _, user := range users {
|
||||||
|
au.storage.Store(user.User, user.Pass)
|
||||||
|
}
|
||||||
|
usernames := make([]string, 0, len(users))
|
||||||
|
au.storage.Range(func(key, value interface{}) bool {
|
||||||
|
usernames = append(usernames, key.(string))
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
au.usernames = usernames
|
||||||
|
|
||||||
|
return au
|
||||||
|
}
|
154
component/dialer/dialer.go
Normal file
154
component/dialer/dialer.go
Normal file
@ -0,0 +1,154 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Dialer() *net.Dialer {
|
||||||
|
dialer := &net.Dialer{}
|
||||||
|
if DialerHook != nil {
|
||||||
|
DialerHook(dialer)
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialer
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenConfig() *net.ListenConfig {
|
||||||
|
cfg := &net.ListenConfig{}
|
||||||
|
if ListenConfigHook != nil {
|
||||||
|
ListenConfigHook(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func Dial(network, address string) (net.Conn, error) {
|
||||||
|
return DialContext(context.Background(), network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer := Dialer()
|
||||||
|
|
||||||
|
var ip net.IP
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
|
default:
|
||||||
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if DialHook != nil {
|
||||||
|
DialHook(dialer, network, ip)
|
||||||
|
}
|
||||||
|
return dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
|
||||||
|
case "tcp", "udp":
|
||||||
|
return dualStackDailContext(ctx, network, address)
|
||||||
|
default:
|
||||||
|
return nil, errors.New("network invalid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenPacket(network, address string) (net.PacketConn, error) {
|
||||||
|
lc := ListenConfig()
|
||||||
|
|
||||||
|
if ListenPacketHook != nil && address == "" {
|
||||||
|
ip := ListenPacketHook()
|
||||||
|
if ip != nil {
|
||||||
|
address = net.JoinHostPort(ip.String(), "0")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lc.ListenPacket(context.Background(), network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dualStackDailContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
returned := make(chan struct{})
|
||||||
|
defer close(returned)
|
||||||
|
|
||||||
|
type dialResult struct {
|
||||||
|
net.Conn
|
||||||
|
error
|
||||||
|
resolved bool
|
||||||
|
ipv6 bool
|
||||||
|
done bool
|
||||||
|
}
|
||||||
|
results := make(chan dialResult)
|
||||||
|
var primary, fallback dialResult
|
||||||
|
|
||||||
|
startRacer := func(ctx context.Context, network, host string, ipv6 bool) {
|
||||||
|
dialer := Dialer()
|
||||||
|
result := dialResult{ipv6: ipv6, done: true}
|
||||||
|
defer func() {
|
||||||
|
select {
|
||||||
|
case results <- result:
|
||||||
|
case <-returned:
|
||||||
|
if result.Conn != nil {
|
||||||
|
result.Conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
var ip net.IP
|
||||||
|
if ipv6 {
|
||||||
|
ip, result.error = resolver.ResolveIPv6(host)
|
||||||
|
} else {
|
||||||
|
ip, result.error = resolver.ResolveIPv4(host)
|
||||||
|
}
|
||||||
|
if result.error != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.resolved = true
|
||||||
|
|
||||||
|
if DialHook != nil {
|
||||||
|
DialHook(dialer, network, ip)
|
||||||
|
}
|
||||||
|
result.Conn, result.error = dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
|
||||||
|
go startRacer(ctx, network+"4", host, false)
|
||||||
|
go startRacer(ctx, network+"6", host, true)
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
|
return res.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if !res.ipv6 {
|
||||||
|
primary = res
|
||||||
|
} else {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
|
||||||
|
if primary.done && fallback.done {
|
||||||
|
if primary.resolved {
|
||||||
|
return nil, primary.error
|
||||||
|
} else if fallback.resolved {
|
||||||
|
return nil, fallback.error
|
||||||
|
} else {
|
||||||
|
return nil, primary.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
142
component/dialer/hook.go
Normal file
142
component/dialer/hook.go
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DialerHookFunc = func(dialer *net.Dialer)
|
||||||
|
type DialHookFunc = func(dialer *net.Dialer, network string, ip net.IP)
|
||||||
|
type ListenConfigHookFunc = func(*net.ListenConfig)
|
||||||
|
type ListenPacketHookFunc = func() net.IP
|
||||||
|
|
||||||
|
var (
|
||||||
|
DialerHook DialerHookFunc
|
||||||
|
DialHook DialHookFunc
|
||||||
|
ListenConfigHook ListenConfigHookFunc
|
||||||
|
ListenPacketHook ListenPacketHookFunc
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrAddrNotFound = errors.New("addr not found")
|
||||||
|
ErrNetworkNotSupport = errors.New("network not support")
|
||||||
|
)
|
||||||
|
|
||||||
|
func lookupTCPAddr(ip net.IP, addrs []net.Addr) (*net.TCPAddr, error) {
|
||||||
|
ipv4 := ip.To4() != nil
|
||||||
|
|
||||||
|
for _, elm := range addrs {
|
||||||
|
addr, ok := elm.(*net.IPNet)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
addrV4 := addr.IP.To4() != nil
|
||||||
|
|
||||||
|
if addrV4 && ipv4 {
|
||||||
|
return &net.TCPAddr{IP: addr.IP, Port: 0}, nil
|
||||||
|
} else if !addrV4 && !ipv4 {
|
||||||
|
return &net.TCPAddr{IP: addr.IP, Port: 0}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrAddrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupUDPAddr(ip net.IP, addrs []net.Addr) (*net.UDPAddr, error) {
|
||||||
|
ipv4 := ip.To4() != nil
|
||||||
|
|
||||||
|
for _, elm := range addrs {
|
||||||
|
addr, ok := elm.(*net.IPNet)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
addrV4 := addr.IP.To4() != nil
|
||||||
|
|
||||||
|
if addrV4 && ipv4 {
|
||||||
|
return &net.UDPAddr{IP: addr.IP, Port: 0}, nil
|
||||||
|
} else if !addrV4 && !ipv4 {
|
||||||
|
return &net.UDPAddr{IP: addr.IP, Port: 0}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrAddrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenPacketWithInterface(name string) ListenPacketHookFunc {
|
||||||
|
single := singledo.NewSingle(5 * time.Second)
|
||||||
|
|
||||||
|
return func() net.IP {
|
||||||
|
elm, err, _ := single.Do(func() (interface{}, error) {
|
||||||
|
iface, err := net.InterfaceByName(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return addrs, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
addrs := elm.([]net.Addr)
|
||||||
|
|
||||||
|
for _, elm := range addrs {
|
||||||
|
addr, ok := elm.(*net.IPNet)
|
||||||
|
if !ok || addr.IP.To4() == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return addr.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func DialerWithInterface(name string) DialHookFunc {
|
||||||
|
single := singledo.NewSingle(5 * time.Second)
|
||||||
|
|
||||||
|
return func(dialer *net.Dialer, network string, ip net.IP) {
|
||||||
|
elm, err, _ := single.Do(func() (interface{}, error) {
|
||||||
|
iface, err := net.InterfaceByName(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return addrs, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
addrs := elm.([]net.Addr)
|
||||||
|
|
||||||
|
switch network {
|
||||||
|
case "tcp", "tcp4", "tcp6":
|
||||||
|
if addr, err := lookupTCPAddr(ip, addrs); err == nil {
|
||||||
|
dialer.LocalAddr = addr
|
||||||
|
}
|
||||||
|
case "udp", "udp4", "udp6":
|
||||||
|
if addr, err := lookupUDPAddr(ip, addrs); err == nil {
|
||||||
|
dialer.LocalAddr = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
26
component/domain-trie/node.go
Normal file
26
component/domain-trie/node.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package trie
|
||||||
|
|
||||||
|
// Node is the trie's node
|
||||||
|
type Node struct {
|
||||||
|
Data interface{}
|
||||||
|
children map[string]*Node
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *Node) getChild(s string) *Node {
|
||||||
|
return n.children[s]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *Node) hasChild(s string) bool {
|
||||||
|
return n.getChild(s) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *Node) addChild(s string, child *Node) {
|
||||||
|
n.children[s] = child
|
||||||
|
}
|
||||||
|
|
||||||
|
func newNode(data interface{}) *Node {
|
||||||
|
return &Node{
|
||||||
|
Data: data,
|
||||||
|
children: map[string]*Node{},
|
||||||
|
}
|
||||||
|
}
|
92
component/domain-trie/tire.go
Normal file
92
component/domain-trie/tire.go
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
package trie
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
wildcard = "*"
|
||||||
|
domainStep = "."
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrInvalidDomain means insert domain is invalid
|
||||||
|
ErrInvalidDomain = errors.New("invalid domain")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Trie contains the main logic for adding and searching nodes for domain segments.
|
||||||
|
// support wildcard domain (e.g *.google.com)
|
||||||
|
type Trie struct {
|
||||||
|
root *Node
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidDomain(domain string) bool {
|
||||||
|
return domain != "" && domain[0] != '.' && domain[len(domain)-1] != '.'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert adds a node to the trie.
|
||||||
|
// Support
|
||||||
|
// 1. www.example.com
|
||||||
|
// 2. *.example.com
|
||||||
|
// 3. subdomain.*.example.com
|
||||||
|
func (t *Trie) Insert(domain string, data interface{}) error {
|
||||||
|
if !isValidDomain(domain) {
|
||||||
|
return ErrInvalidDomain
|
||||||
|
}
|
||||||
|
|
||||||
|
parts := strings.Split(domain, domainStep)
|
||||||
|
node := t.root
|
||||||
|
// reverse storage domain part to save space
|
||||||
|
for i := len(parts) - 1; i >= 0; i-- {
|
||||||
|
part := parts[i]
|
||||||
|
if !node.hasChild(part) {
|
||||||
|
node.addChild(part, newNode(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
node = node.getChild(part)
|
||||||
|
}
|
||||||
|
|
||||||
|
node.Data = data
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search is the most important part of the Trie.
|
||||||
|
// Priority as:
|
||||||
|
// 1. static part
|
||||||
|
// 2. wildcard domain
|
||||||
|
func (t *Trie) Search(domain string) *Node {
|
||||||
|
if !isValidDomain(domain) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
parts := strings.Split(domain, domainStep)
|
||||||
|
|
||||||
|
n := t.root
|
||||||
|
for i := len(parts) - 1; i >= 0; i-- {
|
||||||
|
part := parts[i]
|
||||||
|
|
||||||
|
var child *Node
|
||||||
|
if !n.hasChild(part) {
|
||||||
|
if !n.hasChild(wildcard) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
child = n.getChild(wildcard)
|
||||||
|
} else {
|
||||||
|
child = n.getChild(part)
|
||||||
|
}
|
||||||
|
|
||||||
|
n = child
|
||||||
|
}
|
||||||
|
|
||||||
|
if n.Data == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a new, empty Trie.
|
||||||
|
func New() *Trie {
|
||||||
|
return &Trie{root: newNode(nil)}
|
||||||
|
}
|
87
component/domain-trie/trie_test.go
Normal file
87
component/domain-trie/trie_test.go
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
package trie
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var localIP = net.IP{127, 0, 0, 1}
|
||||||
|
|
||||||
|
func TestTrie_Basic(t *testing.T) {
|
||||||
|
tree := New()
|
||||||
|
domains := []string{
|
||||||
|
"example.com",
|
||||||
|
"google.com",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, domain := range domains {
|
||||||
|
tree.Insert(domain, localIP)
|
||||||
|
}
|
||||||
|
|
||||||
|
node := tree.Search("example.com")
|
||||||
|
if node == nil {
|
||||||
|
t.Error("should not recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !node.Data.(net.IP).Equal(localIP) {
|
||||||
|
t.Error("should equal 127.0.0.1")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Insert("", localIP) == nil {
|
||||||
|
t.Error("should return error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrie_Wildcard(t *testing.T) {
|
||||||
|
tree := New()
|
||||||
|
domains := []string{
|
||||||
|
"*.example.com",
|
||||||
|
"sub.*.example.com",
|
||||||
|
"*.dev",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, domain := range domains {
|
||||||
|
tree.Insert(domain, localIP)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search("sub.example.com") == nil {
|
||||||
|
t.Error("should not recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search("sub.foo.example.com") == nil {
|
||||||
|
t.Error("should not recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search("foo.sub.example.com") != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search("foo.example.dev") != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search("example.com") != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrie_Boundary(t *testing.T) {
|
||||||
|
tree := New()
|
||||||
|
tree.Insert("*.dev", localIP)
|
||||||
|
|
||||||
|
if err := tree.Insert(".", localIP); err == nil {
|
||||||
|
t.Error("should recv err")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tree.Insert(".com", localIP); err == nil {
|
||||||
|
t.Error("should recv err")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search("dev") != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tree.Search(".dev") != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
}
|
141
component/fakeip/pool.go
Normal file
141
component/fakeip/pool.go
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
package fakeip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Pool is a implementation about fake ip generator without storage
|
||||||
|
type Pool struct {
|
||||||
|
max uint32
|
||||||
|
min uint32
|
||||||
|
gateway uint32
|
||||||
|
offset uint32
|
||||||
|
mux sync.Mutex
|
||||||
|
host *trie.Trie
|
||||||
|
cache *cache.LruCache
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup return a fake ip with host
|
||||||
|
func (p *Pool) Lookup(host string) net.IP {
|
||||||
|
p.mux.Lock()
|
||||||
|
defer p.mux.Unlock()
|
||||||
|
if elm, exist := p.cache.Get(host); exist {
|
||||||
|
ip := elm.(net.IP)
|
||||||
|
|
||||||
|
// ensure ip --> host on head of linked list
|
||||||
|
n := ipToUint(ip.To4())
|
||||||
|
offset := n - p.min + 1
|
||||||
|
p.cache.Get(offset)
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := p.get(host)
|
||||||
|
p.cache.Set(host, ip)
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookBack return host with the fake ip
|
||||||
|
func (p *Pool) LookBack(ip net.IP) (string, bool) {
|
||||||
|
p.mux.Lock()
|
||||||
|
defer p.mux.Unlock()
|
||||||
|
|
||||||
|
if ip = ip.To4(); ip == nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
n := ipToUint(ip.To4())
|
||||||
|
offset := n - p.min + 1
|
||||||
|
|
||||||
|
if elm, exist := p.cache.Get(offset); exist {
|
||||||
|
host := elm.(string)
|
||||||
|
|
||||||
|
// ensure host --> ip on head of linked list
|
||||||
|
p.cache.Get(host)
|
||||||
|
return host, true
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupHost return if domain in host
|
||||||
|
func (p *Pool) LookupHost(domain string) bool {
|
||||||
|
if p.host == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return p.host.Search(domain) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exist returns if given ip exists in fake-ip pool
|
||||||
|
func (p *Pool) Exist(ip net.IP) bool {
|
||||||
|
p.mux.Lock()
|
||||||
|
defer p.mux.Unlock()
|
||||||
|
|
||||||
|
if ip = ip.To4(); ip == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
n := ipToUint(ip.To4())
|
||||||
|
offset := n - p.min + 1
|
||||||
|
return p.cache.Exist(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gateway return gateway ip
|
||||||
|
func (p *Pool) Gateway() net.IP {
|
||||||
|
return uintToIP(p.gateway)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pool) get(host string) net.IP {
|
||||||
|
current := p.offset
|
||||||
|
for {
|
||||||
|
p.offset = (p.offset + 1) % (p.max - p.min)
|
||||||
|
// Avoid infinite loops
|
||||||
|
if p.offset == current {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if !p.cache.Exist(p.offset) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ip := uintToIP(p.min + p.offset - 1)
|
||||||
|
p.cache.Set(p.offset, host)
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
func ipToUint(ip net.IP) uint32 {
|
||||||
|
v := uint32(ip[0]) << 24
|
||||||
|
v += uint32(ip[1]) << 16
|
||||||
|
v += uint32(ip[2]) << 8
|
||||||
|
v += uint32(ip[3])
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func uintToIP(v uint32) net.IP {
|
||||||
|
return net.IPv4(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return Pool instance
|
||||||
|
func New(ipnet *net.IPNet, size int, host *trie.Trie) (*Pool, error) {
|
||||||
|
min := ipToUint(ipnet.IP) + 2
|
||||||
|
|
||||||
|
ones, bits := ipnet.Mask.Size()
|
||||||
|
total := 1<<uint(bits-ones) - 2
|
||||||
|
|
||||||
|
if total <= 0 {
|
||||||
|
return nil, errors.New("ipnet don't have valid ip")
|
||||||
|
}
|
||||||
|
|
||||||
|
max := min + uint32(total) - 1
|
||||||
|
return &Pool{
|
||||||
|
min: min,
|
||||||
|
max: max,
|
||||||
|
gateway: min - 1,
|
||||||
|
host: host,
|
||||||
|
cache: cache.NewLRUCache(cache.WithSize(size * 2)),
|
||||||
|
}, nil
|
||||||
|
}
|
78
component/fakeip/pool_test.go
Normal file
78
component/fakeip/pool_test.go
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
package fakeip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPool_Basic(t *testing.T) {
|
||||||
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
||||||
|
pool, _ := New(ipnet, 10, nil)
|
||||||
|
|
||||||
|
first := pool.Lookup("foo.com")
|
||||||
|
last := pool.Lookup("bar.com")
|
||||||
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
|
assert.True(t, first.Equal(net.IP{192, 168, 0, 2}))
|
||||||
|
assert.True(t, last.Equal(net.IP{192, 168, 0, 3}))
|
||||||
|
assert.True(t, exist)
|
||||||
|
assert.Equal(t, bar, "bar.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_Cycle(t *testing.T) {
|
||||||
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/30")
|
||||||
|
pool, _ := New(ipnet, 10, nil)
|
||||||
|
|
||||||
|
first := pool.Lookup("foo.com")
|
||||||
|
same := pool.Lookup("baz.com")
|
||||||
|
|
||||||
|
assert.True(t, first.Equal(same))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_MaxCacheSize(t *testing.T) {
|
||||||
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/24")
|
||||||
|
pool, _ := New(ipnet, 2, nil)
|
||||||
|
|
||||||
|
first := pool.Lookup("foo.com")
|
||||||
|
pool.Lookup("bar.com")
|
||||||
|
pool.Lookup("baz.com")
|
||||||
|
next := pool.Lookup("foo.com")
|
||||||
|
|
||||||
|
assert.False(t, first.Equal(next))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_DoubleMapping(t *testing.T) {
|
||||||
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/24")
|
||||||
|
pool, _ := New(ipnet, 2, nil)
|
||||||
|
|
||||||
|
// fill cache
|
||||||
|
fooIP := pool.Lookup("foo.com")
|
||||||
|
bazIP := pool.Lookup("baz.com")
|
||||||
|
|
||||||
|
// make foo.com hot
|
||||||
|
pool.Lookup("foo.com")
|
||||||
|
|
||||||
|
// should drop baz.com
|
||||||
|
barIP := pool.Lookup("bar.com")
|
||||||
|
|
||||||
|
_, fooExist := pool.LookBack(fooIP)
|
||||||
|
_, bazExist := pool.LookBack(bazIP)
|
||||||
|
_, barExist := pool.LookBack(barIP)
|
||||||
|
|
||||||
|
newBazIP := pool.Lookup("baz.com")
|
||||||
|
|
||||||
|
assert.True(t, fooExist)
|
||||||
|
assert.False(t, bazExist)
|
||||||
|
assert.True(t, barExist)
|
||||||
|
|
||||||
|
assert.False(t, bazIP.Equal(newBazIP))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPool_Error(t *testing.T) {
|
||||||
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/31")
|
||||||
|
_, err := New(ipnet, 10, nil)
|
||||||
|
|
||||||
|
assert.Error(t, err)
|
||||||
|
}
|
35
component/mmdb/mmdb.go
Normal file
35
component/mmdb/mmdb.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package mmdb
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
|
)
|
||||||
|
|
||||||
|
var mmdb *geoip2.Reader
|
||||||
|
var once sync.Once
|
||||||
|
|
||||||
|
func LoadFromBytes(buffer []byte) {
|
||||||
|
once.Do(func() {
|
||||||
|
var err error
|
||||||
|
mmdb, err = geoip2.FromBytes(buffer)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln("Can't load mmdb: %s", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func Instance() *geoip2.Reader {
|
||||||
|
once.Do(func() {
|
||||||
|
var err error
|
||||||
|
mmdb, err = geoip2.Open(C.Path.MMDB())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln("Can't load mmdb: %s", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return mmdb
|
||||||
|
}
|
37
component/nat/table.go
Normal file
37
component/nat/table.go
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
package nat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Table struct {
|
||||||
|
mapping sync.Map
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) Set(key string, pc C.PacketConn) {
|
||||||
|
t.mapping.Store(key, pc)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) Get(key string) C.PacketConn {
|
||||||
|
item, exist := t.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return item.(C.PacketConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) GetOrCreateLock(key string) (*sync.WaitGroup, bool) {
|
||||||
|
item, loaded := t.mapping.LoadOrStore(key, &sync.WaitGroup{})
|
||||||
|
return item.(*sync.WaitGroup), loaded
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) Delete(key string) {
|
||||||
|
t.mapping.Delete(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return *Cache
|
||||||
|
func New() *Table {
|
||||||
|
return &Table{}
|
||||||
|
}
|
119
component/resolver/resolver.go
Normal file
119
component/resolver/resolver.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
package resolver
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// DefaultResolver aim to resolve ip
|
||||||
|
DefaultResolver Resolver
|
||||||
|
|
||||||
|
// DefaultHosts aim to resolve hosts
|
||||||
|
DefaultHosts = trie.New()
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrIPNotFound = errors.New("couldn't find ip")
|
||||||
|
ErrIPVersion = errors.New("ip version error")
|
||||||
|
)
|
||||||
|
|
||||||
|
type Resolver interface {
|
||||||
|
ResolveIP(host string) (ip net.IP, err error)
|
||||||
|
ResolveIPv4(host string) (ip net.IP, err error)
|
||||||
|
ResolveIPv6(host string) (ip net.IP, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIPv4 with a host, return ipv4
|
||||||
|
func ResolveIPv4(host string) (net.IP, error) {
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
if ip := node.Data.(net.IP).To4(); ip != nil {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
if !strings.Contains(host, ":") {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
return nil, ErrIPVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver != nil {
|
||||||
|
return DefaultResolver.ResolveIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
ipAddrs, err := net.LookupIP(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ip := range ipAddrs {
|
||||||
|
if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
return ip4, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIPv6 with a host, return ipv6
|
||||||
|
func ResolveIPv6(host string) (net.IP, error) {
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
if ip := node.Data.(net.IP).To16(); ip != nil {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
if strings.Contains(host, ":") {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
return nil, ErrIPVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver != nil {
|
||||||
|
return DefaultResolver.ResolveIPv6(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
ipAddrs, err := net.LookupIP(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ip := range ipAddrs {
|
||||||
|
if ip.To4() == nil {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIP with a host, return ip
|
||||||
|
func ResolveIP(host string) (net.IP, error) {
|
||||||
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
|
return node.Data.(net.IP), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if DefaultResolver != nil {
|
||||||
|
return DefaultResolver.ResolveIP(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ipAddr.IP, nil
|
||||||
|
}
|
@ -8,6 +8,8 @@ import (
|
|||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
// HTTPObfs is shadowsocks http simple-obfs implementation
|
// HTTPObfs is shadowsocks http simple-obfs implementation
|
||||||
@ -32,15 +34,15 @@ func (ho *HTTPObfs) Read(b []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ho.firstResponse {
|
if ho.firstResponse {
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
n, err := ho.Conn.Read(buf)
|
n, err := ho.Conn.Read(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
idx := bytes.Index(buf[:n], []byte("\r\n\r\n"))
|
idx := bytes.Index(buf[:n], []byte("\r\n\r\n"))
|
||||||
if idx == -1 {
|
if idx == -1 {
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
ho.firstResponse = false
|
ho.firstResponse = false
|
||||||
@ -50,7 +52,7 @@ func (ho *HTTPObfs) Read(b []byte) (int, error) {
|
|||||||
ho.buf = buf[:idx+4+length]
|
ho.buf = buf[:idx+4+length]
|
||||||
ho.offset = idx + 4 + n
|
ho.offset = idx + 4 + n
|
||||||
} else {
|
} else {
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
@ -6,15 +6,18 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rand.Seed(time.Now().Unix())
|
rand.Seed(time.Now().Unix())
|
||||||
}
|
}
|
||||||
|
|
||||||
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, 2048) }}
|
const (
|
||||||
|
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
|
||||||
|
)
|
||||||
|
|
||||||
// TLSObfs is shadowsocks tls simple-obfs implementation
|
// TLSObfs is shadowsocks tls simple-obfs implementation
|
||||||
type TLSObfs struct {
|
type TLSObfs struct {
|
||||||
@ -26,12 +29,12 @@ type TLSObfs struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (to *TLSObfs) read(b []byte, discardN int) (int, error) {
|
func (to *TLSObfs) read(b []byte, discardN int) (int, error) {
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
_, err := io.ReadFull(to.Conn, buf[:discardN])
|
_, err := io.ReadFull(to.Conn, buf[:discardN])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
|
|
||||||
sizeBuf := make([]byte, 2)
|
sizeBuf := make([]byte, 2)
|
||||||
_, err = io.ReadFull(to.Conn, sizeBuf)
|
_, err = io.ReadFull(to.Conn, sizeBuf)
|
||||||
@ -75,8 +78,23 @@ func (to *TLSObfs) Read(b []byte) (int, error) {
|
|||||||
// type + ver = 3
|
// type + ver = 3
|
||||||
return to.read(b, 3)
|
return to.read(b, 3)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (to *TLSObfs) Write(b []byte) (int, error) {
|
func (to *TLSObfs) Write(b []byte) (int, error) {
|
||||||
|
length := len(b)
|
||||||
|
for i := 0; i < length; i += chunkSize {
|
||||||
|
end := i + chunkSize
|
||||||
|
if end > length {
|
||||||
|
end = length
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := to.write(b[i:end])
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return length, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (to *TLSObfs) write(b []byte) (int, error) {
|
||||||
if to.firstRequest {
|
if to.firstRequest {
|
||||||
helloMsg := makeClientHelloMsg(b, to.server)
|
helloMsg := makeClientHelloMsg(b, to.server)
|
||||||
_, err := to.Conn.Write(helloMsg)
|
_, err := to.Conn.Write(helloMsg)
|
||||||
@ -84,7 +102,7 @@ func (to *TLSObfs) Write(b []byte) (int, error) {
|
|||||||
return len(b), err
|
return len(b), err
|
||||||
}
|
}
|
||||||
|
|
||||||
size := bufPool.Get().([]byte)
|
size := pool.BufPool.Get().([]byte)
|
||||||
binary.BigEndian.PutUint16(size[:2], uint16(len(b)))
|
binary.BigEndian.PutUint16(size[:2], uint16(len(b)))
|
||||||
|
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
@ -92,7 +110,7 @@ func (to *TLSObfs) Write(b []byte) (int, error) {
|
|||||||
buf.Write(size[:2])
|
buf.Write(size[:2])
|
||||||
buf.Write(b)
|
buf.Write(b)
|
||||||
_, err := to.Conn.Write(buf.Bytes())
|
_, err := to.Conn.Write(buf.Bytes())
|
||||||
bufPool.Put(size[:cap(size)])
|
pool.BufPool.Put(size[:cap(size)])
|
||||||
return len(b), err
|
return len(b), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -107,9 +125,8 @@ func NewTLSObfs(conn net.Conn, server string) net.Conn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func makeClientHelloMsg(data []byte, server string) []byte {
|
func makeClientHelloMsg(data []byte, server string) []byte {
|
||||||
random := make([]byte, 32)
|
random := make([]byte, 28)
|
||||||
sessionID := make([]byte, 32)
|
sessionID := make([]byte, 32)
|
||||||
size := make([]byte, 2)
|
|
||||||
rand.Read(random)
|
rand.Read(random)
|
||||||
rand.Read(sessionID)
|
rand.Read(sessionID)
|
||||||
|
|
||||||
@ -124,12 +141,12 @@ func makeClientHelloMsg(data []byte, server string) []byte {
|
|||||||
|
|
||||||
// clientHello, length, TLS 1.2 version
|
// clientHello, length, TLS 1.2 version
|
||||||
buf.WriteByte(1)
|
buf.WriteByte(1)
|
||||||
binary.BigEndian.PutUint16(size, uint16(208+len(data)+len(server)))
|
|
||||||
buf.WriteByte(0)
|
buf.WriteByte(0)
|
||||||
buf.Write(size)
|
binary.Write(buf, binary.BigEndian, uint16(208+len(data)+len(server)))
|
||||||
buf.Write([]byte{0x03, 0x03})
|
buf.Write([]byte{0x03, 0x03})
|
||||||
|
|
||||||
// random, sid len, sid
|
// random with timestamp, sid len, sid
|
||||||
|
binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix()))
|
||||||
buf.Write(random)
|
buf.Write(random)
|
||||||
buf.WriteByte(32)
|
buf.WriteByte(32)
|
||||||
buf.Write(sessionID)
|
buf.Write(sessionID)
|
||||||
@ -147,24 +164,19 @@ func makeClientHelloMsg(data []byte, server string) []byte {
|
|||||||
buf.Write([]byte{0x01, 0x00})
|
buf.Write([]byte{0x01, 0x00})
|
||||||
|
|
||||||
// extension length
|
// extension length
|
||||||
binary.BigEndian.PutUint16(size, uint16(79+len(data)+len(server)))
|
binary.Write(buf, binary.BigEndian, uint16(79+len(data)+len(server)))
|
||||||
buf.Write(size)
|
|
||||||
|
|
||||||
// session ticket
|
// session ticket
|
||||||
buf.Write([]byte{0x00, 0x23})
|
buf.Write([]byte{0x00, 0x23})
|
||||||
binary.BigEndian.PutUint16(size, uint16(len(data)))
|
binary.Write(buf, binary.BigEndian, uint16(len(data)))
|
||||||
buf.Write(size)
|
|
||||||
buf.Write(data)
|
buf.Write(data)
|
||||||
|
|
||||||
// server name
|
// server name
|
||||||
buf.Write([]byte{0x00, 0x00})
|
buf.Write([]byte{0x00, 0x00})
|
||||||
binary.BigEndian.PutUint16(size, uint16(len(server)+5))
|
binary.Write(buf, binary.BigEndian, uint16(len(server)+5))
|
||||||
buf.Write(size)
|
binary.Write(buf, binary.BigEndian, uint16(len(server)+3))
|
||||||
binary.BigEndian.PutUint16(size, uint16(len(server)+3))
|
|
||||||
buf.Write(size)
|
|
||||||
buf.WriteByte(0)
|
buf.WriteByte(0)
|
||||||
binary.BigEndian.PutUint16(size, uint16(len(server)))
|
binary.Write(buf, binary.BigEndian, uint16(len(server)))
|
||||||
buf.Write(size)
|
|
||||||
buf.Write([]byte(server))
|
buf.Write([]byte(server))
|
||||||
|
|
||||||
// ec_point
|
// ec_point
|
||||||
|
21
component/snell/cipher.go
Normal file
21
component/snell/cipher.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package snell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/cipher"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type snellCipher struct {
|
||||||
|
psk []byte
|
||||||
|
makeAEAD func(key []byte) (cipher.AEAD, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sc *snellCipher) KeySize() int { return 32 }
|
||||||
|
func (sc *snellCipher) SaltSize() int { return 16 }
|
||||||
|
func (sc *snellCipher) Encrypter(salt []byte) (cipher.AEAD, error) {
|
||||||
|
return sc.makeAEAD(argon2.IDKey(sc.psk, salt, 3, 8, 1, uint32(sc.KeySize())))
|
||||||
|
}
|
||||||
|
func (sc *snellCipher) Decrypter(salt []byte) (cipher.AEAD, error) {
|
||||||
|
return sc.makeAEAD(argon2.IDKey(sc.psk, salt, 3, 8, 1, uint32(sc.KeySize())))
|
||||||
|
}
|
91
component/snell/snell.go
Normal file
91
component/snell/snell.go
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
package snell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
|
||||||
|
"golang.org/x/crypto/chacha20poly1305"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
CommandPing byte = 0
|
||||||
|
CommandConnect byte = 1
|
||||||
|
|
||||||
|
CommandTunnel byte = 0
|
||||||
|
CommandError byte = 2
|
||||||
|
|
||||||
|
Version byte = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bufferPool = sync.Pool{New: func() interface{} { return &bytes.Buffer{} }}
|
||||||
|
)
|
||||||
|
|
||||||
|
type Snell struct {
|
||||||
|
net.Conn
|
||||||
|
buffer [1]byte
|
||||||
|
reply bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Snell) Read(b []byte) (int, error) {
|
||||||
|
if s.reply {
|
||||||
|
return s.Conn.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
s.reply = true
|
||||||
|
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.buffer[0] == CommandTunnel {
|
||||||
|
return s.Conn.Read(b)
|
||||||
|
} else if s.buffer[0] != CommandError {
|
||||||
|
return 0, errors.New("Command not support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// CommandError
|
||||||
|
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
length := int(s.buffer[0])
|
||||||
|
msg := make([]byte, length)
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(s.Conn, msg); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, errors.New(string(msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteHeader(conn net.Conn, host string, port uint) error {
|
||||||
|
buf := bufferPool.Get().(*bytes.Buffer)
|
||||||
|
buf.Reset()
|
||||||
|
defer bufferPool.Put(buf)
|
||||||
|
buf.WriteByte(Version)
|
||||||
|
buf.WriteByte(CommandConnect)
|
||||||
|
|
||||||
|
// clientID length & id
|
||||||
|
buf.WriteByte(0)
|
||||||
|
|
||||||
|
// host & port
|
||||||
|
buf.WriteByte(uint8(len(host)))
|
||||||
|
buf.WriteString(host)
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(port))
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf.Bytes()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func StreamConn(conn net.Conn, psk []byte) net.Conn {
|
||||||
|
cipher := &snellCipher{psk, chacha20poly1305.New}
|
||||||
|
return &Snell{Conn: shadowaead.NewConn(conn, cipher)}
|
||||||
|
}
|
429
component/socks5/socks5.go
Normal file
429
component/socks5/socks5.go
Normal file
@ -0,0 +1,429 @@
|
|||||||
|
package socks5
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Error represents a SOCKS error
|
||||||
|
type Error byte
|
||||||
|
|
||||||
|
func (err Error) Error() string {
|
||||||
|
return "SOCKS error: " + strconv.Itoa(int(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command is request commands as defined in RFC 1928 section 4.
|
||||||
|
type Command = uint8
|
||||||
|
|
||||||
|
// SOCKS request commands as defined in RFC 1928 section 4.
|
||||||
|
const (
|
||||||
|
CmdConnect Command = 1
|
||||||
|
CmdBind Command = 2
|
||||||
|
CmdUDPAssociate Command = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
// SOCKS address types as defined in RFC 1928 section 5.
|
||||||
|
const (
|
||||||
|
AtypIPv4 = 1
|
||||||
|
AtypDomainName = 3
|
||||||
|
AtypIPv6 = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxAddrLen is the maximum size of SOCKS address in bytes.
|
||||||
|
const MaxAddrLen = 1 + 1 + 255 + 2
|
||||||
|
|
||||||
|
// MaxAuthLen is the maximum size of user/password field in SOCKS5 Auth
|
||||||
|
const MaxAuthLen = 255
|
||||||
|
|
||||||
|
// Addr represents a SOCKS address as defined in RFC 1928 section 5.
|
||||||
|
type Addr []byte
|
||||||
|
|
||||||
|
func (a Addr) String() string {
|
||||||
|
var host, port string
|
||||||
|
|
||||||
|
switch a[0] {
|
||||||
|
case AtypDomainName:
|
||||||
|
hostLen := uint16(a[1])
|
||||||
|
host = string(a[2 : 2+hostLen])
|
||||||
|
port = strconv.Itoa((int(a[2+hostLen]) << 8) | int(a[2+hostLen+1]))
|
||||||
|
case AtypIPv4:
|
||||||
|
host = net.IP(a[1 : 1+net.IPv4len]).String()
|
||||||
|
port = strconv.Itoa((int(a[1+net.IPv4len]) << 8) | int(a[1+net.IPv4len+1]))
|
||||||
|
case AtypIPv6:
|
||||||
|
host = net.IP(a[1 : 1+net.IPv6len]).String()
|
||||||
|
port = strconv.Itoa((int(a[1+net.IPv6len]) << 8) | int(a[1+net.IPv6len+1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return net.JoinHostPort(host, port)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UDPAddr converts a socks5.Addr to *net.UDPAddr
|
||||||
|
func (a Addr) UDPAddr() *net.UDPAddr {
|
||||||
|
if len(a) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch a[0] {
|
||||||
|
case AtypIPv4:
|
||||||
|
var ip [net.IPv4len]byte
|
||||||
|
copy(ip[0:], a[1:1+net.IPv4len])
|
||||||
|
return &net.UDPAddr{IP: net.IP(ip[:]), Port: int(binary.BigEndian.Uint16(a[1+net.IPv4len : 1+net.IPv4len+2]))}
|
||||||
|
case AtypIPv6:
|
||||||
|
var ip [net.IPv6len]byte
|
||||||
|
copy(ip[0:], a[1:1+net.IPv6len])
|
||||||
|
return &net.UDPAddr{IP: net.IP(ip[:]), Port: int(binary.BigEndian.Uint16(a[1+net.IPv6len : 1+net.IPv6len+2]))}
|
||||||
|
}
|
||||||
|
// Other Atyp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SOCKS errors as defined in RFC 1928 section 6.
|
||||||
|
const (
|
||||||
|
ErrGeneralFailure = Error(1)
|
||||||
|
ErrConnectionNotAllowed = Error(2)
|
||||||
|
ErrNetworkUnreachable = Error(3)
|
||||||
|
ErrHostUnreachable = Error(4)
|
||||||
|
ErrConnectionRefused = Error(5)
|
||||||
|
ErrTTLExpired = Error(6)
|
||||||
|
ErrCommandNotSupported = Error(7)
|
||||||
|
ErrAddressNotSupported = Error(8)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Auth errors used to return a specific "Auth failed" error
|
||||||
|
var ErrAuth = errors.New("auth failed")
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
Username string
|
||||||
|
Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerHandshake fast-tracks SOCKS initialization to get target address to connect on server side.
|
||||||
|
func ServerHandshake(rw net.Conn, authenticator auth.Authenticator) (addr Addr, command Command, err error) {
|
||||||
|
// Read RFC 1928 for request and reply structure and sizes.
|
||||||
|
buf := make([]byte, MaxAddrLen)
|
||||||
|
// read VER, NMETHODS, METHODS
|
||||||
|
if _, err = io.ReadFull(rw, buf[:2]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nmethods := buf[1]
|
||||||
|
if _, err = io.ReadFull(rw, buf[:nmethods]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// write VER METHOD
|
||||||
|
if authenticator != nil {
|
||||||
|
if _, err = rw.Write([]byte{5, 2}); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get header
|
||||||
|
header := make([]byte, 2)
|
||||||
|
if _, err = io.ReadFull(rw, header); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
authBuf := make([]byte, MaxAuthLen)
|
||||||
|
// Get username
|
||||||
|
userLen := int(header[1])
|
||||||
|
if userLen <= 0 {
|
||||||
|
rw.Write([]byte{1, 1})
|
||||||
|
err = ErrAuth
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = io.ReadFull(rw, authBuf[:userLen]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user := string(authBuf[:userLen])
|
||||||
|
|
||||||
|
// Get password
|
||||||
|
if _, err = rw.Read(header[:1]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passLen := int(header[0])
|
||||||
|
if passLen <= 0 {
|
||||||
|
rw.Write([]byte{1, 1})
|
||||||
|
err = ErrAuth
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = io.ReadFull(rw, authBuf[:passLen]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pass := string(authBuf[:passLen])
|
||||||
|
|
||||||
|
// Verify
|
||||||
|
if ok := authenticator.Verify(string(user), string(pass)); !ok {
|
||||||
|
rw.Write([]byte{1, 1})
|
||||||
|
err = ErrAuth
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response auth state
|
||||||
|
if _, err = rw.Write([]byte{1, 0}); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if _, err = rw.Write([]byte{5, 0}); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// read VER CMD RSV ATYP DST.ADDR DST.PORT
|
||||||
|
if _, err = io.ReadFull(rw, buf[:3]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
command = buf[1]
|
||||||
|
addr, err = ReadAddr(rw, buf)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch command {
|
||||||
|
case CmdConnect, CmdUDPAssociate:
|
||||||
|
// Acquire server listened address info
|
||||||
|
localAddr := ParseAddr(rw.LocalAddr().String())
|
||||||
|
if localAddr == nil {
|
||||||
|
err = ErrAddressNotSupported
|
||||||
|
} else {
|
||||||
|
// write VER REP RSV ATYP BND.ADDR BND.PORT
|
||||||
|
_, err = rw.Write(bytes.Join([][]byte{{5, 0, 0}, localAddr}, []byte{}))
|
||||||
|
}
|
||||||
|
case CmdBind:
|
||||||
|
fallthrough
|
||||||
|
default:
|
||||||
|
err = ErrCommandNotSupported
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientHandshake fast-tracks SOCKS initialization to get target address to connect on client side.
|
||||||
|
func ClientHandshake(rw io.ReadWriter, addr Addr, command Command, user *User) (Addr, error) {
|
||||||
|
buf := make([]byte, MaxAddrLen)
|
||||||
|
var err error
|
||||||
|
|
||||||
|
// VER, NMETHODS, METHODS
|
||||||
|
if user != nil {
|
||||||
|
_, err = rw.Write([]byte{5, 1, 2})
|
||||||
|
} else {
|
||||||
|
_, err = rw.Write([]byte{5, 1, 0})
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// VER, METHOD
|
||||||
|
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[0] != 5 {
|
||||||
|
return nil, errors.New("SOCKS version error")
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[1] == 2 {
|
||||||
|
// password protocol version
|
||||||
|
authMsg := &bytes.Buffer{}
|
||||||
|
authMsg.WriteByte(1)
|
||||||
|
authMsg.WriteByte(uint8(len(user.Username)))
|
||||||
|
authMsg.WriteString(user.Username)
|
||||||
|
authMsg.WriteByte(uint8(len(user.Password)))
|
||||||
|
authMsg.WriteString(user.Password)
|
||||||
|
|
||||||
|
if _, err := rw.Write(authMsg.Bytes()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[1] != 0 {
|
||||||
|
return nil, errors.New("rejected username/password")
|
||||||
|
}
|
||||||
|
} else if buf[1] != 0 {
|
||||||
|
return nil, errors.New("SOCKS need auth")
|
||||||
|
}
|
||||||
|
|
||||||
|
// VER, CMD, RSV, ADDR
|
||||||
|
if _, err := rw.Write(bytes.Join([][]byte{{5, command, 0}, addr}, []byte{})); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// VER, REP, RSV
|
||||||
|
if _, err := io.ReadFull(rw, buf[:3]); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ReadAddr(rw, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReadAddr(r io.Reader, b []byte) (Addr, error) {
|
||||||
|
if len(b) < MaxAddrLen {
|
||||||
|
return nil, io.ErrShortBuffer
|
||||||
|
}
|
||||||
|
_, err := io.ReadFull(r, b[:1]) // read 1st byte for address type
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch b[0] {
|
||||||
|
case AtypDomainName:
|
||||||
|
_, err = io.ReadFull(r, b[1:2]) // read 2nd byte for domain length
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
domainLength := uint16(b[1])
|
||||||
|
_, err = io.ReadFull(r, b[2:2+domainLength+2])
|
||||||
|
return b[:1+1+domainLength+2], err
|
||||||
|
case AtypIPv4:
|
||||||
|
_, err = io.ReadFull(r, b[1:1+net.IPv4len+2])
|
||||||
|
return b[:1+net.IPv4len+2], err
|
||||||
|
case AtypIPv6:
|
||||||
|
_, err = io.ReadFull(r, b[1:1+net.IPv6len+2])
|
||||||
|
return b[:1+net.IPv6len+2], err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrAddressNotSupported
|
||||||
|
}
|
||||||
|
|
||||||
|
// SplitAddr slices a SOCKS address from beginning of b. Returns nil if failed.
|
||||||
|
func SplitAddr(b []byte) Addr {
|
||||||
|
addrLen := 1
|
||||||
|
if len(b) < addrLen {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch b[0] {
|
||||||
|
case AtypDomainName:
|
||||||
|
if len(b) < 2 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
addrLen = 1 + 1 + int(b[1]) + 2
|
||||||
|
case AtypIPv4:
|
||||||
|
addrLen = 1 + net.IPv4len + 2
|
||||||
|
case AtypIPv6:
|
||||||
|
addrLen = 1 + net.IPv6len + 2
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(b) < addrLen {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return b[:addrLen]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseAddr parses the address in string s. Returns nil if failed.
|
||||||
|
func ParseAddr(s string) Addr {
|
||||||
|
var addr Addr
|
||||||
|
host, port, err := net.SplitHostPort(s)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
addr = make([]byte, 1+net.IPv4len+2)
|
||||||
|
addr[0] = AtypIPv4
|
||||||
|
copy(addr[1:], ip4)
|
||||||
|
} else {
|
||||||
|
addr = make([]byte, 1+net.IPv6len+2)
|
||||||
|
addr[0] = AtypIPv6
|
||||||
|
copy(addr[1:], ip)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if len(host) > 255 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
addr = make([]byte, 1+1+len(host)+2)
|
||||||
|
addr[0] = AtypDomainName
|
||||||
|
addr[1] = byte(len(host))
|
||||||
|
copy(addr[2:], host)
|
||||||
|
}
|
||||||
|
|
||||||
|
portnum, err := strconv.ParseUint(port, 10, 16)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
addr[len(addr)-2], addr[len(addr)-1] = byte(portnum>>8), byte(portnum)
|
||||||
|
|
||||||
|
return addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseAddrToSocksAddr parse a socks addr from net.addr
|
||||||
|
// This is a fast path of ParseAddr(addr.String())
|
||||||
|
func ParseAddrToSocksAddr(addr net.Addr) Addr {
|
||||||
|
var hostip net.IP
|
||||||
|
var port int
|
||||||
|
if udpaddr, ok := addr.(*net.UDPAddr); ok {
|
||||||
|
hostip = udpaddr.IP
|
||||||
|
port = udpaddr.Port
|
||||||
|
} else if tcpaddr, ok := addr.(*net.TCPAddr); ok {
|
||||||
|
hostip = tcpaddr.IP
|
||||||
|
port = tcpaddr.Port
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallback parse
|
||||||
|
if hostip == nil {
|
||||||
|
return ParseAddr(addr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed Addr
|
||||||
|
if ip4 := hostip.To4(); ip4.DefaultMask() != nil {
|
||||||
|
parsed = make([]byte, 1+net.IPv4len+2)
|
||||||
|
parsed[0] = AtypIPv4
|
||||||
|
copy(parsed[1:], ip4)
|
||||||
|
binary.BigEndian.PutUint16(parsed[1+net.IPv4len:], uint16(port))
|
||||||
|
|
||||||
|
} else {
|
||||||
|
parsed = make([]byte, 1+net.IPv6len+2)
|
||||||
|
parsed[0] = AtypIPv6
|
||||||
|
copy(parsed[1:], hostip)
|
||||||
|
binary.BigEndian.PutUint16(parsed[1+net.IPv6len:], uint16(port))
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeUDPPacket split `packet` to addr payload, and this function is mutable with `packet`
|
||||||
|
func DecodeUDPPacket(packet []byte) (addr Addr, payload []byte, err error) {
|
||||||
|
if len(packet) < 5 {
|
||||||
|
err = errors.New("insufficient length of packet")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// packet[0] and packet[1] are reserved
|
||||||
|
if !bytes.Equal(packet[:2], []byte{0, 0}) {
|
||||||
|
err = errors.New("reserved fields should be zero")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if packet[2] != 0 /* fragments */ {
|
||||||
|
err = errors.New("discarding fragmented payload")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = SplitAddr(packet[3:])
|
||||||
|
if addr == nil {
|
||||||
|
err = errors.New("failed to read UDP header")
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = packet[3+len(addr):]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeUDPPacket(addr Addr, payload []byte) (packet []byte, err error) {
|
||||||
|
if addr == nil {
|
||||||
|
err = errors.New("address is invalid")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
packet = bytes.Join([][]byte{{0, 0, 0}, addr, payload}, []byte{})
|
||||||
|
return
|
||||||
|
}
|
223
component/trojan/trojan.go
Normal file
223
component/trojan/trojan.go
Normal file
@ -0,0 +1,223 @@
|
|||||||
|
package trojan
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/binary"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// max packet length
|
||||||
|
maxLength = 8192
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
defaultALPN = []string{"h2", "http/1.1"}
|
||||||
|
crlf = []byte{'\r', '\n'}
|
||||||
|
|
||||||
|
bufPool = sync.Pool{New: func() interface{} { return &bytes.Buffer{} }}
|
||||||
|
)
|
||||||
|
|
||||||
|
type Command = byte
|
||||||
|
|
||||||
|
var (
|
||||||
|
CommandTCP byte = 1
|
||||||
|
CommandUDP byte = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
type Option struct {
|
||||||
|
Password string
|
||||||
|
ALPN []string
|
||||||
|
ServerName string
|
||||||
|
SkipCertVerify bool
|
||||||
|
ClientSessionCache tls.ClientSessionCache
|
||||||
|
}
|
||||||
|
|
||||||
|
type Trojan struct {
|
||||||
|
option *Option
|
||||||
|
hexPassword []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) StreamConn(conn net.Conn) (net.Conn, error) {
|
||||||
|
alpn := defaultALPN
|
||||||
|
if len(t.option.ALPN) != 0 {
|
||||||
|
alpn = t.option.ALPN
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
NextProtos: alpn,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
InsecureSkipVerify: t.option.SkipCertVerify,
|
||||||
|
ServerName: t.option.ServerName,
|
||||||
|
ClientSessionCache: t.option.ClientSessionCache,
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConn := tls.Client(conn, tlsConfig)
|
||||||
|
if err := tlsConn.Handshake(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tlsConn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) WriteHeader(w io.Writer, command Command, socks5Addr []byte) error {
|
||||||
|
buf := bufPool.Get().(*bytes.Buffer)
|
||||||
|
defer buf.Reset()
|
||||||
|
defer bufPool.Put(buf)
|
||||||
|
|
||||||
|
buf.Write(t.hexPassword)
|
||||||
|
buf.Write(crlf)
|
||||||
|
|
||||||
|
buf.WriteByte(command)
|
||||||
|
buf.Write(socks5Addr)
|
||||||
|
buf.Write(crlf)
|
||||||
|
|
||||||
|
_, err := w.Write(buf.Bytes())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) PacketConn(conn net.Conn) net.PacketConn {
|
||||||
|
return &PacketConn{
|
||||||
|
Conn: conn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writePacket(w io.Writer, socks5Addr, payload []byte) (int, error) {
|
||||||
|
buf := bufPool.Get().(*bytes.Buffer)
|
||||||
|
defer buf.Reset()
|
||||||
|
defer bufPool.Put(buf)
|
||||||
|
|
||||||
|
buf.Write(socks5Addr)
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(len(payload)))
|
||||||
|
buf.Write(crlf)
|
||||||
|
buf.Write(payload)
|
||||||
|
|
||||||
|
return w.Write(buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func WritePacket(w io.Writer, socks5Addr, payload []byte) (int, error) {
|
||||||
|
if len(payload) <= maxLength {
|
||||||
|
return writePacket(w, socks5Addr, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
offset := 0
|
||||||
|
total := len(payload)
|
||||||
|
for {
|
||||||
|
cursor := offset + maxLength
|
||||||
|
if cursor > total {
|
||||||
|
cursor = total
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := writePacket(w, socks5Addr, payload[offset:cursor])
|
||||||
|
if err != nil {
|
||||||
|
return offset + n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
offset = cursor
|
||||||
|
if offset == total {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReadPacket(r io.Reader, payload []byte) (net.Addr, int, int, error) {
|
||||||
|
addr, err := socks5.ReadAddr(r, payload)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, 0, errors.New("read addr error")
|
||||||
|
}
|
||||||
|
uAddr := addr.UDPAddr()
|
||||||
|
|
||||||
|
if _, err = io.ReadFull(r, payload[:2]); err != nil {
|
||||||
|
return nil, 0, 0, errors.New("read length error")
|
||||||
|
}
|
||||||
|
|
||||||
|
total := int(binary.BigEndian.Uint16(payload[:2]))
|
||||||
|
if total > maxLength {
|
||||||
|
return nil, 0, 0, errors.New("packet invalid")
|
||||||
|
}
|
||||||
|
|
||||||
|
// read crlf
|
||||||
|
if _, err = io.ReadFull(r, payload[:2]); err != nil {
|
||||||
|
return nil, 0, 0, errors.New("read crlf error")
|
||||||
|
}
|
||||||
|
|
||||||
|
length := len(payload)
|
||||||
|
if total < length {
|
||||||
|
length = total
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = io.ReadFull(r, payload[:length]); err != nil {
|
||||||
|
return nil, 0, 0, errors.New("read packet error")
|
||||||
|
}
|
||||||
|
|
||||||
|
return uAddr, length, total - length, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(option *Option) *Trojan {
|
||||||
|
return &Trojan{option, hexSha224([]byte(option.Password))}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PacketConn struct {
|
||||||
|
net.Conn
|
||||||
|
remain int
|
||||||
|
rAddr net.Addr
|
||||||
|
mux sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
return WritePacket(pc, socks5.ParseAddr(addr.String()), b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
pc.mux.Lock()
|
||||||
|
defer pc.mux.Unlock()
|
||||||
|
if pc.remain != 0 {
|
||||||
|
length := len(b)
|
||||||
|
if pc.remain < length {
|
||||||
|
length = pc.remain
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := pc.Conn.Read(b[:length])
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc.remain -= n
|
||||||
|
addr := pc.rAddr
|
||||||
|
if pc.remain == 0 {
|
||||||
|
pc.rAddr = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return n, addr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, n, remain, err := ReadPacket(pc.Conn, b)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if remain != 0 {
|
||||||
|
pc.remain = remain
|
||||||
|
pc.rAddr = addr
|
||||||
|
}
|
||||||
|
|
||||||
|
return n, addr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hexSha224(data []byte) []byte {
|
||||||
|
buf := make([]byte, 56)
|
||||||
|
hash := sha256.New224()
|
||||||
|
hash.Write(data)
|
||||||
|
hex.Encode(buf, hash.Sum(nil))
|
||||||
|
return buf
|
||||||
|
}
|
173
component/v2ray-plugin/mux.go
Normal file
173
component/v2ray-plugin/mux.go
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
package obfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SessionStatus = byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
SessionStatusNew SessionStatus = 0x01
|
||||||
|
SessionStatusKeep SessionStatus = 0x02
|
||||||
|
SessionStatusEnd SessionStatus = 0x03
|
||||||
|
SessionStatusKeepAlive SessionStatus = 0x04
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
OptionNone = byte(0x00)
|
||||||
|
OptionData = byte(0x01)
|
||||||
|
OptionError = byte(0x02)
|
||||||
|
)
|
||||||
|
|
||||||
|
type MuxOption struct {
|
||||||
|
ID [2]byte
|
||||||
|
Port uint16
|
||||||
|
Host string
|
||||||
|
Type string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mux is an mux-compatible client for v2ray-plugin, not a complete implementation
|
||||||
|
type Mux struct {
|
||||||
|
net.Conn
|
||||||
|
buf bytes.Buffer
|
||||||
|
id [2]byte
|
||||||
|
length [2]byte
|
||||||
|
status [2]byte
|
||||||
|
otb []byte
|
||||||
|
remain int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mux) Read(b []byte) (int, error) {
|
||||||
|
if m.remain != 0 {
|
||||||
|
length := m.remain
|
||||||
|
if len(b) < m.remain {
|
||||||
|
length = len(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := m.Conn.Read(b[:length])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
m.remain -= n
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
_, err := io.ReadFull(m.Conn, m.length[:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
length := binary.BigEndian.Uint16(m.length[:])
|
||||||
|
if length > 512 {
|
||||||
|
return 0, errors.New("invalid metalen")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.ReadFull(m.Conn, m.id[:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = m.Conn.Read(m.status[:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
opcode := m.status[0]
|
||||||
|
if opcode == SessionStatusKeepAlive {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := m.status[1]
|
||||||
|
|
||||||
|
if opts != OptionData {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.ReadFull(m.Conn, m.length[:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
dataLen := int(binary.BigEndian.Uint16(m.length[:]))
|
||||||
|
m.remain = dataLen
|
||||||
|
if dataLen > len(b) {
|
||||||
|
dataLen = len(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := m.Conn.Read(b[:dataLen])
|
||||||
|
m.remain -= n
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mux) Write(b []byte) (int, error) {
|
||||||
|
if m.otb != nil {
|
||||||
|
// create a sub connection
|
||||||
|
if _, err := m.Conn.Write(m.otb); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
m.otb = nil
|
||||||
|
}
|
||||||
|
m.buf.Reset()
|
||||||
|
binary.Write(&m.buf, binary.BigEndian, uint16(4))
|
||||||
|
m.buf.Write(m.id[:])
|
||||||
|
m.buf.WriteByte(SessionStatusKeep)
|
||||||
|
m.buf.WriteByte(OptionData)
|
||||||
|
binary.Write(&m.buf, binary.BigEndian, uint16(len(b)))
|
||||||
|
m.buf.Write(b)
|
||||||
|
|
||||||
|
return m.Conn.Write(m.buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mux) Close() error {
|
||||||
|
_, err := m.Conn.Write([]byte{0x0, 0x4, m.id[0], m.id[1], SessionStatusEnd, OptionNone})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.Conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMux(conn net.Conn, option MuxOption) *Mux {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
|
||||||
|
// fill empty length
|
||||||
|
buf.Write([]byte{0x0, 0x0})
|
||||||
|
buf.Write(option.ID[:])
|
||||||
|
buf.WriteByte(SessionStatusNew)
|
||||||
|
buf.WriteByte(OptionNone)
|
||||||
|
|
||||||
|
// tcp
|
||||||
|
netType := byte(0x1)
|
||||||
|
if option.Type == "udp" {
|
||||||
|
netType = byte(0x2)
|
||||||
|
}
|
||||||
|
buf.WriteByte(netType)
|
||||||
|
|
||||||
|
// port
|
||||||
|
binary.Write(buf, binary.BigEndian, option.Port)
|
||||||
|
|
||||||
|
// address
|
||||||
|
ip := net.ParseIP(option.Host)
|
||||||
|
if ip == nil {
|
||||||
|
buf.WriteByte(0x2)
|
||||||
|
buf.WriteString(option.Host)
|
||||||
|
} else if ipv4 := ip.To4(); ipv4 != nil {
|
||||||
|
buf.WriteByte(0x1)
|
||||||
|
buf.Write(ipv4)
|
||||||
|
} else {
|
||||||
|
buf.WriteByte(0x3)
|
||||||
|
buf.Write(ip.To16())
|
||||||
|
}
|
||||||
|
|
||||||
|
metadata := buf.Bytes()
|
||||||
|
binary.BigEndian.PutUint16(metadata[:2], uint16(len(metadata)-2))
|
||||||
|
|
||||||
|
return &Mux{
|
||||||
|
Conn: conn,
|
||||||
|
id: option.ID,
|
||||||
|
otb: metadata,
|
||||||
|
}
|
||||||
|
}
|
49
component/v2ray-plugin/websocket.go
Normal file
49
component/v2ray-plugin/websocket.go
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package obfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/vmess"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Option is options of websocket obfs
|
||||||
|
type Option struct {
|
||||||
|
Host string
|
||||||
|
Path string
|
||||||
|
Headers map[string]string
|
||||||
|
TLSConfig *tls.Config
|
||||||
|
Mux bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewV2rayObfs return a HTTPObfs
|
||||||
|
func NewV2rayObfs(conn net.Conn, option *Option) (net.Conn, error) {
|
||||||
|
header := http.Header{}
|
||||||
|
for k, v := range option.Headers {
|
||||||
|
header.Add(k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
config := &vmess.WebsocketConfig{
|
||||||
|
Host: option.Host,
|
||||||
|
Path: option.Path,
|
||||||
|
TLS: option.TLSConfig != nil,
|
||||||
|
Headers: header,
|
||||||
|
TLSConfig: option.TLSConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
conn, err = vmess.NewWebsocketConn(conn, config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Mux {
|
||||||
|
conn = NewMux(conn, MuxOption{
|
||||||
|
ID: [2]byte{0, 0},
|
||||||
|
Host: "127.0.0.1",
|
||||||
|
Port: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
@ -5,6 +5,8 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
type aeadWriter struct {
|
type aeadWriter struct {
|
||||||
@ -20,8 +22,8 @@ func newAEADWriter(w io.Writer, aead cipher.AEAD, iv []byte) *aeadWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *aeadWriter) Write(b []byte) (n int, err error) {
|
func (w *aeadWriter) Write(b []byte) (n int, err error) {
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
defer bufPool.Put(buf[:cap(buf)])
|
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||||
length := len(b)
|
length := len(b)
|
||||||
for {
|
for {
|
||||||
if length == 0 {
|
if length == 0 {
|
||||||
@ -71,7 +73,7 @@ func (r *aeadReader) Read(b []byte) (int, error) {
|
|||||||
n := copy(b, r.buf[r.offset:])
|
n := copy(b, r.buf[r.offset:])
|
||||||
r.offset += n
|
r.offset += n
|
||||||
if r.offset == len(r.buf) {
|
if r.offset == len(r.buf) {
|
||||||
bufPool.Put(r.buf[:cap(r.buf)])
|
pool.BufPool.Put(r.buf[:cap(r.buf)])
|
||||||
r.buf = nil
|
r.buf = nil
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
@ -87,10 +89,10 @@ func (r *aeadReader) Read(b []byte) (int, error) {
|
|||||||
return 0, errors.New("Buffer is larger than standard")
|
return 0, errors.New("Buffer is larger than standard")
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
_, err = io.ReadFull(r.Reader, buf[:size])
|
_, err = io.ReadFull(r.Reader, buf[:size])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,7 +107,7 @@ func (r *aeadReader) Read(b []byte) (int, error) {
|
|||||||
realLen := size - r.Overhead()
|
realLen := size - r.Overhead()
|
||||||
n := copy(b, buf[:realLen])
|
n := copy(b, buf[:realLen])
|
||||||
if len(b) >= realLen {
|
if len(b) >= realLen {
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,7 +4,8 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"sync"
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -13,8 +14,6 @@ const (
|
|||||||
maxSize = 17 * 1024 // 2 + chunkSize + aead.Overhead()
|
maxSize = 17 * 1024 // 2 + chunkSize + aead.Overhead()
|
||||||
)
|
)
|
||||||
|
|
||||||
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, maxSize) }}
|
|
||||||
|
|
||||||
type chunkReader struct {
|
type chunkReader struct {
|
||||||
io.Reader
|
io.Reader
|
||||||
buf []byte
|
buf []byte
|
||||||
@ -35,7 +34,7 @@ func (cr *chunkReader) Read(b []byte) (int, error) {
|
|||||||
n := copy(b, cr.buf[cr.offset:])
|
n := copy(b, cr.buf[cr.offset:])
|
||||||
cr.offset += n
|
cr.offset += n
|
||||||
if cr.offset == len(cr.buf) {
|
if cr.offset == len(cr.buf) {
|
||||||
bufPool.Put(cr.buf[:cap(cr.buf)])
|
pool.BufPool.Put(cr.buf[:cap(cr.buf)])
|
||||||
cr.buf = nil
|
cr.buf = nil
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
@ -60,10 +59,10 @@ func (cr *chunkReader) Read(b []byte) (int, error) {
|
|||||||
return size, nil
|
return size, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
_, err = io.ReadFull(cr.Reader, buf[:size])
|
_, err = io.ReadFull(cr.Reader, buf[:size])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
n := copy(b, cr.buf[:])
|
n := copy(b, cr.buf[:])
|
||||||
@ -77,8 +76,8 @@ type chunkWriter struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cw *chunkWriter) Write(b []byte) (n int, err error) {
|
func (cw *chunkWriter) Write(b []byte) (n int, err error) {
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
defer bufPool.Put(buf[:cap(buf)])
|
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||||
length := len(b)
|
length := len(b)
|
||||||
for {
|
for {
|
||||||
if length == 0 {
|
if length == 0 {
|
||||||
|
@ -35,20 +35,10 @@ type Conn struct {
|
|||||||
respV byte
|
respV byte
|
||||||
security byte
|
security byte
|
||||||
|
|
||||||
sent bool
|
|
||||||
received bool
|
received bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (vc *Conn) Write(b []byte) (int, error) {
|
func (vc *Conn) Write(b []byte) (int, error) {
|
||||||
if vc.sent {
|
|
||||||
return vc.writer.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := vc.sendRequest(); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
vc.sent = true
|
|
||||||
return vc.writer.Write(b)
|
return vc.writer.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,11 +55,10 @@ func (vc *Conn) Read(b []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (vc *Conn) sendRequest() error {
|
func (vc *Conn) sendRequest() error {
|
||||||
timestamp := make([]byte, 8)
|
timestamp := time.Now()
|
||||||
binary.BigEndian.PutUint64(timestamp, uint64(time.Now().UTC().Unix()))
|
|
||||||
|
|
||||||
h := hmac.New(md5.New, vc.id.UUID.Bytes())
|
h := hmac.New(md5.New, vc.id.UUID.Bytes())
|
||||||
h.Write(timestamp)
|
binary.Write(h, binary.BigEndian, uint64(timestamp.Unix()))
|
||||||
_, err := vc.Conn.Write(h.Sum(nil))
|
_, err := vc.Conn.Write(h.Sum(nil))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -88,7 +77,11 @@ func (vc *Conn) sendRequest() error {
|
|||||||
// P Sec Reserve Cmd
|
// P Sec Reserve Cmd
|
||||||
buf.WriteByte(byte(p<<4) | byte(vc.security))
|
buf.WriteByte(byte(p<<4) | byte(vc.security))
|
||||||
buf.WriteByte(0)
|
buf.WriteByte(0)
|
||||||
buf.WriteByte(CommandTCP)
|
if vc.dst.UDP {
|
||||||
|
buf.WriteByte(CommandUDP)
|
||||||
|
} else {
|
||||||
|
buf.WriteByte(CommandTCP)
|
||||||
|
}
|
||||||
|
|
||||||
// Port AddrType Addr
|
// Port AddrType Addr
|
||||||
binary.Write(buf, binary.BigEndian, uint16(vc.dst.Port))
|
binary.Write(buf, binary.BigEndian, uint16(vc.dst.Port))
|
||||||
@ -111,7 +104,7 @@ func (vc *Conn) sendRequest() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
stream := cipher.NewCFBEncrypter(block, hashTimestamp(time.Now().UTC()))
|
stream := cipher.NewCFBEncrypter(block, hashTimestamp(timestamp))
|
||||||
stream.XORKeyStream(buf.Bytes(), buf.Bytes())
|
stream.XORKeyStream(buf.Bytes(), buf.Bytes())
|
||||||
_, err = vc.Conn.Write(buf.Bytes())
|
_, err = vc.Conn.Write(buf.Bytes())
|
||||||
return err
|
return err
|
||||||
@ -145,7 +138,7 @@ func (vc *Conn) recvResponse() error {
|
|||||||
func hashTimestamp(t time.Time) []byte {
|
func hashTimestamp(t time.Time) []byte {
|
||||||
md5hash := md5.New()
|
md5hash := md5.New()
|
||||||
ts := make([]byte, 8)
|
ts := make([]byte, 8)
|
||||||
binary.BigEndian.PutUint64(ts, uint64(t.UTC().Unix()))
|
binary.BigEndian.PutUint64(ts, uint64(t.Unix()))
|
||||||
md5hash.Write(ts)
|
md5hash.Write(ts)
|
||||||
md5hash.Write(ts)
|
md5hash.Write(ts)
|
||||||
md5hash.Write(ts)
|
md5hash.Write(ts)
|
||||||
@ -154,7 +147,7 @@ func hashTimestamp(t time.Time) []byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// newConn return a Conn instance
|
// newConn return a Conn instance
|
||||||
func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) (*Conn, error) {
|
||||||
randBytes := make([]byte, 33)
|
randBytes := make([]byte, 33)
|
||||||
rand.Read(randBytes)
|
rand.Read(randBytes)
|
||||||
reqBodyIV := make([]byte, 16)
|
reqBodyIV := make([]byte, 16)
|
||||||
@ -197,7 +190,7 @@ func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
|||||||
reader = newAEADReader(conn, aead, respBodyIV[:])
|
reader = newAEADReader(conn, aead, respBodyIV[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Conn{
|
c := &Conn{
|
||||||
Conn: conn,
|
Conn: conn,
|
||||||
id: id,
|
id: id,
|
||||||
dst: dst,
|
dst: dst,
|
||||||
@ -210,4 +203,8 @@ func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
|||||||
writer: writer,
|
writer: writer,
|
||||||
security: security,
|
security: security,
|
||||||
}
|
}
|
||||||
|
if err := c.sendRequest(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
}
|
}
|
||||||
|
@ -5,12 +5,11 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"sync"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid"
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Version of vmess
|
// Version of vmess
|
||||||
@ -39,6 +38,11 @@ var CipherMapping = map[string]byte{
|
|||||||
"chacha20-poly1305": SecurityCHACHA20POLY1305,
|
"chacha20-poly1305": SecurityCHACHA20POLY1305,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
clientSessionCache tls.ClientSessionCache
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
// Command types
|
// Command types
|
||||||
const (
|
const (
|
||||||
CommandTCP byte = 1
|
CommandTCP byte = 1
|
||||||
@ -54,6 +58,7 @@ const (
|
|||||||
|
|
||||||
// DstAddr store destination address
|
// DstAddr store destination address
|
||||||
type DstAddr struct {
|
type DstAddr struct {
|
||||||
|
UDP bool
|
||||||
AddrType byte
|
AddrType byte
|
||||||
Addr []byte
|
Addr []byte
|
||||||
Port uint
|
Port uint
|
||||||
@ -61,76 +66,43 @@ type DstAddr struct {
|
|||||||
|
|
||||||
// Client is vmess connection generator
|
// Client is vmess connection generator
|
||||||
type Client struct {
|
type Client struct {
|
||||||
user []*ID
|
user []*ID
|
||||||
uuid *uuid.UUID
|
uuid *uuid.UUID
|
||||||
security Security
|
security Security
|
||||||
tls bool
|
tls bool
|
||||||
host string
|
host string
|
||||||
websocket bool
|
wsConfig *WebsocketConfig
|
||||||
websocketPath string
|
tlsConfig *tls.Config
|
||||||
skipCertVerify bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config of vmess
|
// Config of vmess
|
||||||
type Config struct {
|
type Config struct {
|
||||||
UUID string
|
UUID string
|
||||||
AlterID uint16
|
AlterID uint16
|
||||||
Security string
|
Security string
|
||||||
TLS bool
|
TLS bool
|
||||||
Host string
|
HostName string
|
||||||
NetWork string
|
Port string
|
||||||
WebSocketPath string
|
NetWork string
|
||||||
SkipCertVerify bool
|
WebSocketPath string
|
||||||
|
WebSocketHeaders map[string]string
|
||||||
|
SkipCertVerify bool
|
||||||
|
SessionCache tls.ClientSessionCache
|
||||||
}
|
}
|
||||||
|
|
||||||
// New return a Conn with net.Conn and DstAddr
|
// New return a Conn with net.Conn and DstAddr
|
||||||
func (c *Client) New(conn net.Conn, dst *DstAddr) (net.Conn, error) {
|
func (c *Client) New(conn net.Conn, dst *DstAddr) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
r := rand.Intn(len(c.user))
|
r := rand.Intn(len(c.user))
|
||||||
if c.websocket {
|
if c.wsConfig != nil {
|
||||||
dialer := &websocket.Dialer{
|
conn, err = NewWebsocketConn(conn, c.wsConfig)
|
||||||
NetDial: func(network, addr string) (net.Conn, error) {
|
|
||||||
return conn, nil
|
|
||||||
},
|
|
||||||
ReadBufferSize: 4 * 1024,
|
|
||||||
WriteBufferSize: 4 * 1024,
|
|
||||||
HandshakeTimeout: time.Second * 8,
|
|
||||||
}
|
|
||||||
scheme := "ws"
|
|
||||||
if c.tls {
|
|
||||||
scheme = "wss"
|
|
||||||
dialer.TLSClientConfig = &tls.Config{
|
|
||||||
InsecureSkipVerify: c.skipCertVerify,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
host, port, err := net.SplitHostPort(c.host)
|
|
||||||
if (scheme == "ws" && port != "80") || (scheme == "wss" && port != "443") {
|
|
||||||
host = c.host
|
|
||||||
}
|
|
||||||
|
|
||||||
uri := url.URL{
|
|
||||||
Scheme: scheme,
|
|
||||||
Host: host,
|
|
||||||
Path: c.websocketPath,
|
|
||||||
}
|
|
||||||
|
|
||||||
wsConn, resp, err := dialer.Dial(uri.String(), nil)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var reason string
|
return nil, err
|
||||||
if resp != nil {
|
|
||||||
reason = resp.Status
|
|
||||||
}
|
|
||||||
println(uri.String(), err.Error())
|
|
||||||
return nil, fmt.Errorf("Dial %s error: %s", host, reason)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
conn = newWebsocketConn(wsConn, conn.RemoteAddr())
|
|
||||||
} else if c.tls {
|
} else if c.tls {
|
||||||
conn = tls.Client(conn, &tls.Config{
|
conn = tls.Client(conn, c.tlsConfig)
|
||||||
InsecureSkipVerify: c.skipCertVerify,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return newConn(conn, c.user[r], dst, c.security), nil
|
return newConn(conn, c.user[r], dst, c.security)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient return Client instance
|
// NewClient return Client instance
|
||||||
@ -161,13 +133,53 @@ func NewClient(config Config) (*Client, error) {
|
|||||||
return nil, fmt.Errorf("Unknown network type: %s", config.NetWork)
|
return nil, fmt.Errorf("Unknown network type: %s", config.NetWork)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
header := http.Header{}
|
||||||
|
for k, v := range config.WebSocketHeaders {
|
||||||
|
header.Add(k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
host := net.JoinHostPort(config.HostName, config.Port)
|
||||||
|
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if config.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
ServerName: config.HostName,
|
||||||
|
InsecureSkipVerify: config.SkipCertVerify,
|
||||||
|
ClientSessionCache: config.SessionCache,
|
||||||
|
}
|
||||||
|
if tlsConfig.ClientSessionCache == nil {
|
||||||
|
tlsConfig.ClientSessionCache = getClientSessionCache()
|
||||||
|
}
|
||||||
|
if host := header.Get("Host"); host != "" {
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var wsConfig *WebsocketConfig
|
||||||
|
if config.NetWork == "ws" {
|
||||||
|
wsConfig = &WebsocketConfig{
|
||||||
|
Host: host,
|
||||||
|
Path: config.WebSocketPath,
|
||||||
|
Headers: header,
|
||||||
|
TLS: config.TLS,
|
||||||
|
TLSConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &Client{
|
return &Client{
|
||||||
user: newAlterIDs(newID(&uid), config.AlterID),
|
user: newAlterIDs(newID(&uid), config.AlterID),
|
||||||
uuid: &uid,
|
uuid: &uid,
|
||||||
security: security,
|
security: security,
|
||||||
tls: config.TLS,
|
tls: config.TLS,
|
||||||
host: config.Host,
|
host: host,
|
||||||
websocket: config.NetWork == "ws",
|
wsConfig: wsConfig,
|
||||||
websocketPath: config.WebSocketPath,
|
tlsConfig: tlsConfig,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getClientSessionCache() tls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
clientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return clientSessionCache
|
||||||
|
}
|
||||||
|
@ -1,10 +1,14 @@
|
|||||||
package vmess
|
package vmess
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
@ -14,10 +18,24 @@ type websocketConn struct {
|
|||||||
conn *websocket.Conn
|
conn *websocket.Conn
|
||||||
reader io.Reader
|
reader io.Reader
|
||||||
remoteAddr net.Addr
|
remoteAddr net.Addr
|
||||||
|
|
||||||
|
// https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency
|
||||||
|
rMux sync.Mutex
|
||||||
|
wMux sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
type WebsocketConfig struct {
|
||||||
|
Host string
|
||||||
|
Path string
|
||||||
|
Headers http.Header
|
||||||
|
TLS bool
|
||||||
|
TLSConfig *tls.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read implements net.Conn.Read()
|
// Read implements net.Conn.Read()
|
||||||
func (wsc *websocketConn) Read(b []byte) (int, error) {
|
func (wsc *websocketConn) Read(b []byte) (int, error) {
|
||||||
|
wsc.rMux.Lock()
|
||||||
|
defer wsc.rMux.Unlock()
|
||||||
for {
|
for {
|
||||||
reader, err := wsc.getReader()
|
reader, err := wsc.getReader()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -35,6 +53,8 @@ func (wsc *websocketConn) Read(b []byte) (int, error) {
|
|||||||
|
|
||||||
// Write implements io.Writer.
|
// Write implements io.Writer.
|
||||||
func (wsc *websocketConn) Write(b []byte) (int, error) {
|
func (wsc *websocketConn) Write(b []byte) (int, error) {
|
||||||
|
wsc.wMux.Lock()
|
||||||
|
defer wsc.wMux.Unlock()
|
||||||
if err := wsc.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
|
if err := wsc.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
@ -91,9 +111,51 @@ func (wsc *websocketConn) SetWriteDeadline(t time.Time) error {
|
|||||||
return wsc.conn.SetWriteDeadline(t)
|
return wsc.conn.SetWriteDeadline(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newWebsocketConn(conn *websocket.Conn, remoteAddr net.Addr) net.Conn {
|
func NewWebsocketConn(conn net.Conn, c *WebsocketConfig) (net.Conn, error) {
|
||||||
return &websocketConn{
|
dialer := &websocket.Dialer{
|
||||||
conn: conn,
|
NetDial: func(network, addr string) (net.Conn, error) {
|
||||||
remoteAddr: remoteAddr,
|
return conn, nil
|
||||||
|
},
|
||||||
|
ReadBufferSize: 4 * 1024,
|
||||||
|
WriteBufferSize: 4 * 1024,
|
||||||
|
HandshakeTimeout: time.Second * 8,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
scheme := "ws"
|
||||||
|
if c.TLS {
|
||||||
|
scheme = "wss"
|
||||||
|
dialer.TLSClientConfig = c.TLSConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
host, port, _ := net.SplitHostPort(c.Host)
|
||||||
|
if (scheme == "ws" && port != "80") || (scheme == "wss" && port != "443") {
|
||||||
|
host = c.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := url.URL{
|
||||||
|
Scheme: scheme,
|
||||||
|
Host: host,
|
||||||
|
Path: c.Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
headers := http.Header{}
|
||||||
|
if c.Headers != nil {
|
||||||
|
for k := range c.Headers {
|
||||||
|
headers.Add(k, c.Headers.Get(k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
wsConn, resp, err := dialer.Dial(uri.String(), headers)
|
||||||
|
if err != nil {
|
||||||
|
reason := err.Error()
|
||||||
|
if resp != nil {
|
||||||
|
reason = resp.Status
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("Dial %s error: %s", host, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &websocketConn{
|
||||||
|
conn: wsConn,
|
||||||
|
remoteAddr: conn.RemoteAddr(),
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
853
config/config.go
853
config/config.go
@ -1,451 +1,628 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"net"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
"github.com/Dreamacro/clash/common/observable"
|
"github.com/Dreamacro/clash/adapters/outboundgroup"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
|
"github.com/Dreamacro/clash/component/fakeip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/dns"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
R "github.com/Dreamacro/clash/rules"
|
R "github.com/Dreamacro/clash/rules"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
yaml "gopkg.in/yaml.v2"
|
yaml "gopkg.in/yaml.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
config *Config
|
|
||||||
once sync.Once
|
|
||||||
)
|
|
||||||
|
|
||||||
// General config
|
// General config
|
||||||
type General struct {
|
type General struct {
|
||||||
Port int
|
Port int `json:"port"`
|
||||||
SocksPort int
|
SocksPort int `json:"socks-port"`
|
||||||
RedirPort int
|
RedirPort int `json:"redir-port"`
|
||||||
AllowLan bool
|
Authentication []string `json:"authentication"`
|
||||||
Mode Mode
|
AllowLan bool `json:"allow-lan"`
|
||||||
LogLevel C.LogLevel
|
BindAddress string `json:"bind-address"`
|
||||||
|
Mode T.TunnelMode `json:"mode"`
|
||||||
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
|
ExternalController string `json:"-"`
|
||||||
|
ExternalUI string `json:"-"`
|
||||||
|
Secret string `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyConfig is update proxy schema
|
// DNS config
|
||||||
type ProxyConfig struct {
|
type DNS struct {
|
||||||
Port *int
|
Enable bool `yaml:"enable"`
|
||||||
SocksPort *int
|
IPv6 bool `yaml:"ipv6"`
|
||||||
RedirPort *int
|
NameServer []dns.NameServer `yaml:"nameserver"`
|
||||||
AllowLan *bool
|
Fallback []dns.NameServer `yaml:"fallback"`
|
||||||
|
FallbackFilter FallbackFilter `yaml:"fallback-filter"`
|
||||||
|
Listen string `yaml:"listen"`
|
||||||
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
|
DefaultNameserver []dns.NameServer `yaml:"default-nameserver"`
|
||||||
|
FakeIPRange *fakeip.Pool
|
||||||
}
|
}
|
||||||
|
|
||||||
// RawConfig is raw config struct
|
// FallbackFilter config
|
||||||
type RawConfig struct {
|
type FallbackFilter struct {
|
||||||
Port int `yaml:"port"`
|
GeoIP bool `yaml:"geoip"`
|
||||||
SocksPort int `yaml:"socks-port"`
|
IPCIDR []*net.IPNet `yaml:"ipcidr"`
|
||||||
RedirPort int `yaml:"redir-port"`
|
}
|
||||||
AllowLan bool `yaml:"allow-lan"`
|
|
||||||
Mode string `yaml:"mode"`
|
|
||||||
LogLevel string `yaml:"log-level"`
|
|
||||||
ExternalController string `yaml:"external-controller"`
|
|
||||||
Secret string `yaml:"secret"`
|
|
||||||
|
|
||||||
Proxy []map[string]interface{} `yaml:"Proxy"`
|
// Experimental config
|
||||||
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
type Experimental struct {
|
||||||
Rule []string `yaml:"Rule"`
|
IgnoreResolveFail bool `yaml:"ignore-resolve-fail"`
|
||||||
|
Interface string `yaml:"interface-name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config is clash config manager
|
// Config is clash config manager
|
||||||
type Config struct {
|
type Config struct {
|
||||||
general *General
|
General *General
|
||||||
rules []C.Rule
|
DNS *DNS
|
||||||
proxies map[string]C.Proxy
|
Experimental *Experimental
|
||||||
lastUpdate time.Time
|
Hosts *trie.Trie
|
||||||
|
Rules []C.Rule
|
||||||
event chan<- interface{}
|
Users []auth.AuthUser
|
||||||
reportCh chan interface{}
|
Proxies map[string]C.Proxy
|
||||||
observable *observable.Observable
|
Providers map[string]provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
// Event is event of clash config
|
type RawDNS struct {
|
||||||
type Event struct {
|
Enable bool `yaml:"enable"`
|
||||||
Type string
|
IPv6 bool `yaml:"ipv6"`
|
||||||
Payload interface{}
|
NameServer []string `yaml:"nameserver"`
|
||||||
|
Fallback []string `yaml:"fallback"`
|
||||||
|
FallbackFilter RawFallbackFilter `yaml:"fallback-filter"`
|
||||||
|
Listen string `yaml:"listen"`
|
||||||
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
|
FakeIPRange string `yaml:"fake-ip-range"`
|
||||||
|
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
||||||
|
DefaultNameserver []string `yaml:"default-nameserver"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subscribe config stream
|
type RawFallbackFilter struct {
|
||||||
func (c *Config) Subscribe() observable.Subscription {
|
GeoIP bool `yaml:"geoip"`
|
||||||
sub, _ := c.observable.Subscribe()
|
IPCIDR []string `yaml:"ipcidr"`
|
||||||
return sub
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Report return a channel for collecting report message
|
type RawConfig struct {
|
||||||
func (c *Config) Report() chan<- interface{} {
|
Port int `yaml:"port"`
|
||||||
return c.reportCh
|
SocksPort int `yaml:"socks-port"`
|
||||||
}
|
RedirPort int `yaml:"redir-port"`
|
||||||
|
Authentication []string `yaml:"authentication"`
|
||||||
|
AllowLan bool `yaml:"allow-lan"`
|
||||||
|
BindAddress string `yaml:"bind-address"`
|
||||||
|
Mode T.TunnelMode `yaml:"mode"`
|
||||||
|
LogLevel log.LogLevel `yaml:"log-level"`
|
||||||
|
ExternalController string `yaml:"external-controller"`
|
||||||
|
ExternalUI string `yaml:"external-ui"`
|
||||||
|
Secret string `yaml:"secret"`
|
||||||
|
|
||||||
func (c *Config) readConfig() (*RawConfig, error) {
|
ProxyProvider map[string]map[string]interface{} `yaml:"proxy-providers"`
|
||||||
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
return nil, err
|
DNS RawDNS `yaml:"dns"`
|
||||||
}
|
Experimental Experimental `yaml:"experimental"`
|
||||||
data, err := ioutil.ReadFile(C.Path.Config())
|
Proxy []map[string]interface{} `yaml:"proxies"`
|
||||||
if err != nil {
|
ProxyGroup []map[string]interface{} `yaml:"proxy-groups"`
|
||||||
return nil, err
|
Rule []string `yaml:"rules"`
|
||||||
}
|
|
||||||
|
|
||||||
if len(data) == 0 {
|
// remove after 1.0
|
||||||
return nil, fmt.Errorf("Configuration file %s is empty", C.Path.Config())
|
ProxyProviderOld map[string]map[string]interface{} `yaml:"proxy-provider"`
|
||||||
}
|
ProxyOld []map[string]interface{} `yaml:"Proxy"`
|
||||||
|
ProxyGroupOld []map[string]interface{} `yaml:"Proxy Group"`
|
||||||
// config with some default value
|
RuleOld []string `yaml:"Rule"`
|
||||||
rawConfig := &RawConfig{
|
|
||||||
AllowLan: false,
|
|
||||||
Mode: Rule.String(),
|
|
||||||
LogLevel: C.INFO.String(),
|
|
||||||
Rule: []string{},
|
|
||||||
Proxy: []map[string]interface{}{},
|
|
||||||
ProxyGroup: []map[string]interface{}{},
|
|
||||||
}
|
|
||||||
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
|
||||||
return rawConfig, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse config
|
// Parse config
|
||||||
func (c *Config) Parse() error {
|
func Parse(buf []byte) (*Config, error) {
|
||||||
cfg, err := c.readConfig()
|
rawCfg, err := UnmarshalRawConfig(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.parseGeneral(cfg); err != nil {
|
return ParseRawConfig(rawCfg)
|
||||||
return err
|
}
|
||||||
|
|
||||||
|
func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||||
|
// config with some default value
|
||||||
|
rawCfg := &RawConfig{
|
||||||
|
AllowLan: false,
|
||||||
|
BindAddress: "*",
|
||||||
|
Mode: T.Rule,
|
||||||
|
Authentication: []string{},
|
||||||
|
LogLevel: log.INFO,
|
||||||
|
Hosts: map[string]string{},
|
||||||
|
Rule: []string{},
|
||||||
|
Proxy: []map[string]interface{}{},
|
||||||
|
ProxyGroup: []map[string]interface{}{},
|
||||||
|
Experimental: Experimental{
|
||||||
|
IgnoreResolveFail: true,
|
||||||
|
},
|
||||||
|
DNS: RawDNS{
|
||||||
|
Enable: false,
|
||||||
|
FakeIPRange: "198.18.0.1/16",
|
||||||
|
FallbackFilter: RawFallbackFilter{
|
||||||
|
GeoIP: true,
|
||||||
|
IPCIDR: []string{},
|
||||||
|
},
|
||||||
|
DefaultNameserver: []string{
|
||||||
|
"114.114.114.114",
|
||||||
|
"8.8.8.8",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// remove after 1.0
|
||||||
|
RuleOld: []string{},
|
||||||
|
ProxyOld: []map[string]interface{}{},
|
||||||
|
ProxyGroupOld: []map[string]interface{}{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.parseProxies(cfg); err != nil {
|
if err := yaml.Unmarshal(buf, &rawCfg); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.parseRules(cfg)
|
return rawCfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Proxies return proxies of clash
|
func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||||
func (c *Config) Proxies() map[string]C.Proxy {
|
config := &Config{}
|
||||||
return c.proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rules return rules of clash
|
config.Experimental = &rawCfg.Experimental
|
||||||
func (c *Config) Rules() []C.Rule {
|
|
||||||
return c.rules
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetMode change mode of clash
|
general, err := parseGeneral(rawCfg)
|
||||||
func (c *Config) SetMode(mode Mode) {
|
|
||||||
c.general.Mode = mode
|
|
||||||
c.event <- &Event{Type: "mode", Payload: mode}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetLogLevel change log level of clash
|
|
||||||
func (c *Config) SetLogLevel(level C.LogLevel) {
|
|
||||||
c.general.LogLevel = level
|
|
||||||
c.event <- &Event{Type: "log-level", Payload: level}
|
|
||||||
}
|
|
||||||
|
|
||||||
// General return clash general config
|
|
||||||
func (c *Config) General() General {
|
|
||||||
return *c.general
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateRules is a function for hot reload rules
|
|
||||||
func (c *Config) UpdateRules() error {
|
|
||||||
cfg, err := c.readConfig()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
config.General = general
|
||||||
|
|
||||||
return c.parseRules(cfg)
|
proxies, providers, err := parseProxies(rawCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Proxies = proxies
|
||||||
|
config.Providers = providers
|
||||||
|
|
||||||
|
rules, err := parseRules(rawCfg, proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Rules = rules
|
||||||
|
|
||||||
|
dnsCfg, err := parseDNS(rawCfg.DNS)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.DNS = dnsCfg
|
||||||
|
|
||||||
|
hosts, err := parseHosts(rawCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Hosts = hosts
|
||||||
|
|
||||||
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) parseGeneral(cfg *RawConfig) error {
|
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||||
port := cfg.Port
|
port := cfg.Port
|
||||||
socksPort := cfg.SocksPort
|
socksPort := cfg.SocksPort
|
||||||
redirPort := cfg.RedirPort
|
redirPort := cfg.RedirPort
|
||||||
allowLan := cfg.AllowLan
|
allowLan := cfg.AllowLan
|
||||||
logLevelString := cfg.LogLevel
|
bindAddress := cfg.BindAddress
|
||||||
modeString := cfg.Mode
|
externalController := cfg.ExternalController
|
||||||
|
externalUI := cfg.ExternalUI
|
||||||
|
secret := cfg.Secret
|
||||||
|
mode := cfg.Mode
|
||||||
|
logLevel := cfg.LogLevel
|
||||||
|
|
||||||
mode, exist := ModeMapping[modeString]
|
if externalUI != "" {
|
||||||
if !exist {
|
externalUI = C.Path.Resolve(externalUI)
|
||||||
return fmt.Errorf("General.mode value invalid")
|
|
||||||
|
if _, err := os.Stat(externalUI); os.IsNotExist(err) {
|
||||||
|
return nil, fmt.Errorf("external-ui: %s not exist", externalUI)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logLevel, exist := C.LogLevelMapping[logLevelString]
|
general := &General{
|
||||||
if !exist {
|
Port: port,
|
||||||
return fmt.Errorf("General.log-level value invalid")
|
SocksPort: socksPort,
|
||||||
|
RedirPort: redirPort,
|
||||||
|
AllowLan: allowLan,
|
||||||
|
BindAddress: bindAddress,
|
||||||
|
Mode: mode,
|
||||||
|
LogLevel: logLevel,
|
||||||
|
ExternalController: externalController,
|
||||||
|
ExternalUI: externalUI,
|
||||||
|
Secret: secret,
|
||||||
}
|
}
|
||||||
|
return general, nil
|
||||||
c.general = &General{
|
|
||||||
Port: port,
|
|
||||||
SocksPort: socksPort,
|
|
||||||
RedirPort: redirPort,
|
|
||||||
AllowLan: allowLan,
|
|
||||||
Mode: mode,
|
|
||||||
LogLevel: logLevel,
|
|
||||||
}
|
|
||||||
|
|
||||||
if restAddr := cfg.ExternalController; restAddr != "" {
|
|
||||||
c.event <- &Event{Type: "external-controller", Payload: restAddr}
|
|
||||||
c.event <- &Event{Type: "secret", Payload: cfg.Secret}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.UpdateGeneral(*c.general)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateGeneral dispatch update event
|
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]provider.ProxyProvider, err error) {
|
||||||
func (c *Config) UpdateGeneral(general General) {
|
proxies = make(map[string]C.Proxy)
|
||||||
c.UpdateProxy(ProxyConfig{
|
providersMap = make(map[string]provider.ProxyProvider)
|
||||||
Port: &general.Port,
|
proxyList := []string{}
|
||||||
SocksPort: &general.SocksPort,
|
|
||||||
RedirPort: &general.RedirPort,
|
|
||||||
AllowLan: &general.AllowLan,
|
|
||||||
})
|
|
||||||
c.event <- &Event{Type: "mode", Payload: general.Mode}
|
|
||||||
c.event <- &Event{Type: "log-level", Payload: general.LogLevel}
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateProxy dispatch update proxy event
|
|
||||||
func (c *Config) UpdateProxy(pc ProxyConfig) {
|
|
||||||
if pc.AllowLan != nil {
|
|
||||||
c.general.AllowLan = *pc.AllowLan
|
|
||||||
}
|
|
||||||
|
|
||||||
c.general.Port = *or(pc.Port, &c.general.Port)
|
|
||||||
if c.general.Port != 0 && (pc.AllowLan != nil || pc.Port != nil) {
|
|
||||||
c.event <- &Event{Type: "http-addr", Payload: genAddr(c.general.Port, c.general.AllowLan)}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.general.SocksPort = *or(pc.SocksPort, &c.general.SocksPort)
|
|
||||||
if c.general.SocksPort != 0 && (pc.AllowLan != nil || pc.SocksPort != nil) {
|
|
||||||
c.event <- &Event{Type: "socks-addr", Payload: genAddr(c.general.SocksPort, c.general.AllowLan)}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.general.RedirPort = *or(pc.RedirPort, &c.general.RedirPort)
|
|
||||||
if c.general.RedirPort != 0 && (pc.AllowLan != nil || pc.RedirPort != nil) {
|
|
||||||
c.event <- &Event{Type: "redir-addr", Payload: genAddr(c.general.RedirPort, c.general.AllowLan)}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) parseProxies(cfg *RawConfig) error {
|
|
||||||
proxies := make(map[string]C.Proxy)
|
|
||||||
proxiesConfig := cfg.Proxy
|
proxiesConfig := cfg.Proxy
|
||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
|
providersConfig := cfg.ProxyProvider
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
if len(proxiesConfig) == 0 {
|
||||||
|
proxiesConfig = cfg.ProxyOld
|
||||||
|
}
|
||||||
|
|
||||||
proxies["DIRECT"] = adapters.NewDirect()
|
if len(groupsConfig) == 0 {
|
||||||
proxies["REJECT"] = adapters.NewReject()
|
groupsConfig = cfg.ProxyGroupOld
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(providersConfig) == 0 {
|
||||||
|
providersConfig = cfg.ProxyProviderOld
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
// Destroy already created provider when err != nil
|
||||||
|
if err != nil {
|
||||||
|
for _, provider := range providersMap {
|
||||||
|
provider.Destroy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
proxies["DIRECT"] = outbound.NewProxy(outbound.NewDirect())
|
||||||
|
proxies["REJECT"] = outbound.NewProxy(outbound.NewReject())
|
||||||
|
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||||
|
|
||||||
// parse proxy
|
// parse proxy
|
||||||
for idx, mapping := range proxiesConfig {
|
for idx, mapping := range proxiesConfig {
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxy, err := outbound.ParseProxy(mapping)
|
||||||
if !existType {
|
|
||||||
return fmt.Errorf("Proxy %d missing type", idx)
|
|
||||||
}
|
|
||||||
|
|
||||||
var proxy C.Proxy
|
|
||||||
var err error
|
|
||||||
switch proxyType {
|
|
||||||
case "ss":
|
|
||||||
ssOption := &adapters.ShadowSocksOption{}
|
|
||||||
err = decoder.Decode(mapping, ssOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = adapters.NewShadowSocks(*ssOption)
|
|
||||||
case "socks5":
|
|
||||||
socksOption := &adapters.Socks5Option{}
|
|
||||||
err = decoder.Decode(mapping, socksOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = adapters.NewSocks5(*socksOption)
|
|
||||||
case "vmess":
|
|
||||||
vmessOption := &adapters.VmessOption{}
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = adapters.NewVmess(*vmessOption)
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Proxy [%d]: %s", idx, err.Error())
|
return nil, nil, fmt.Errorf("Proxy %d: %w", idx, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, exist := proxies[proxy.Name()]; exist {
|
if _, exist := proxies[proxy.Name()]; exist {
|
||||||
return fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
return nil, nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
||||||
}
|
}
|
||||||
proxies[proxy.Name()] = proxy
|
proxies[proxy.Name()] = proxy
|
||||||
|
proxyList = append(proxyList, proxy.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// keep the origional order of ProxyGroups in config file
|
||||||
|
for idx, mapping := range groupsConfig {
|
||||||
|
groupName, existName := mapping["name"].(string)
|
||||||
|
if !existName {
|
||||||
|
return nil, nil, fmt.Errorf("ProxyGroup %d: missing name", idx)
|
||||||
|
}
|
||||||
|
proxyList = append(proxyList, groupName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if any loop exists and sort the ProxyGroups
|
||||||
|
if err := proxyGroupsDagSort(groupsConfig); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse and initial providers
|
||||||
|
for name, mapping := range providersConfig {
|
||||||
|
if name == provider.ReservedName {
|
||||||
|
return nil, nil, fmt.Errorf("can not defined a provider called `%s`", provider.ReservedName)
|
||||||
|
}
|
||||||
|
|
||||||
|
pd, err := provider.ParseProxyProvider(name, mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providersMap[name] = pd
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, provider := range providersMap {
|
||||||
|
log.Infoln("Start initial provider %s", provider.Name())
|
||||||
|
if err := provider.Initial(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse proxy group
|
// parse proxy group
|
||||||
for idx, mapping := range groupsConfig {
|
for idx, mapping := range groupsConfig {
|
||||||
groupType, existType := mapping["type"].(string)
|
group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap)
|
||||||
groupName, existName := mapping["name"].(string)
|
|
||||||
if !existType && existName {
|
|
||||||
return fmt.Errorf("ProxyGroup %d: missing type or name", idx)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, exist := proxies[groupName]; exist {
|
|
||||||
return fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
|
||||||
}
|
|
||||||
var group C.Proxy
|
|
||||||
var err error
|
|
||||||
switch groupType {
|
|
||||||
case "url-test":
|
|
||||||
urlTestOption := &adapters.URLTestOption{}
|
|
||||||
err = decoder.Decode(mapping, urlTestOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
ps, err := getProxies(proxies, urlTestOption.Proxies)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
|
||||||
}
|
|
||||||
group, err = adapters.NewURLTest(*urlTestOption, ps)
|
|
||||||
case "select":
|
|
||||||
selectorOption := &adapters.SelectorOption{}
|
|
||||||
err = decoder.Decode(mapping, selectorOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
ps, err := getProxies(proxies, selectorOption.Proxies)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
|
||||||
}
|
|
||||||
group, err = adapters.NewSelector(selectorOption.Name, ps)
|
|
||||||
case "fallback":
|
|
||||||
fallbackOption := &adapters.FallbackOption{}
|
|
||||||
err = decoder.Decode(mapping, fallbackOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
ps, err := getProxies(proxies, fallbackOption.Proxies)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
|
||||||
}
|
|
||||||
group, err = adapters.NewFallback(*fallbackOption, ps)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Proxy %s: %s", groupName, err.Error())
|
return nil, nil, fmt.Errorf("ProxyGroup[%d]: %w", idx, err)
|
||||||
}
|
}
|
||||||
proxies[groupName] = group
|
|
||||||
|
groupName := group.Name()
|
||||||
|
if _, exist := proxies[groupName]; exist {
|
||||||
|
return nil, nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies[groupName] = outbound.NewProxy(group)
|
||||||
}
|
}
|
||||||
|
|
||||||
var ps []C.Proxy
|
// initial compatible provider
|
||||||
for _, v := range proxies {
|
for _, pd := range providersMap {
|
||||||
ps = append(ps, v)
|
if pd.VehicleType() != provider.Compatible {
|
||||||
}
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
proxies["GLOBAL"], _ = adapters.NewSelector("GLOBAL", ps)
|
log.Infoln("Start initial compatible provider %s", pd.Name())
|
||||||
|
if err := pd.Initial(); err != nil {
|
||||||
// close old goroutine
|
return nil, nil, err
|
||||||
for _, proxy := range c.proxies {
|
|
||||||
switch raw := proxy.(type) {
|
|
||||||
case *adapters.URLTest:
|
|
||||||
raw.Close()
|
|
||||||
case *adapters.Fallback:
|
|
||||||
raw.Close()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c.proxies = proxies
|
|
||||||
c.event <- &Event{Type: "proxies", Payload: proxies}
|
ps := []C.Proxy{}
|
||||||
return nil
|
for _, v := range proxyList {
|
||||||
|
ps = append(ps, proxies[v])
|
||||||
|
}
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0)
|
||||||
|
pd, _ := provider.NewCompatibleProvider(provider.ReservedName, ps, hc)
|
||||||
|
providersMap[provider.ReservedName] = pd
|
||||||
|
|
||||||
|
global := outboundgroup.NewSelector("GLOBAL", []provider.ProxyProvider{pd})
|
||||||
|
proxies["GLOBAL"] = outbound.NewProxy(global)
|
||||||
|
return proxies, providersMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) parseRules(cfg *RawConfig) error {
|
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
||||||
rules := []C.Rule{}
|
rules := []C.Rule{}
|
||||||
|
|
||||||
rulesConfig := cfg.Rule
|
rulesConfig := cfg.Rule
|
||||||
|
|
||||||
|
// remove after 1.0
|
||||||
|
if len(rulesConfig) == 0 {
|
||||||
|
rulesConfig = cfg.RuleOld
|
||||||
|
}
|
||||||
|
|
||||||
// parse rules
|
// parse rules
|
||||||
for _, line := range rulesConfig {
|
for idx, line := range rulesConfig {
|
||||||
rule := strings.Split(line, ",")
|
rule := trimArr(strings.Split(line, ","))
|
||||||
if len(rule) < 3 {
|
var (
|
||||||
continue
|
payload string
|
||||||
|
target string
|
||||||
|
params = []string{}
|
||||||
|
)
|
||||||
|
|
||||||
|
switch l := len(rule); {
|
||||||
|
case l == 2:
|
||||||
|
target = rule[1]
|
||||||
|
case l == 3:
|
||||||
|
payload = rule[1]
|
||||||
|
target = rule[2]
|
||||||
|
case l >= 4:
|
||||||
|
payload = rule[1]
|
||||||
|
target = rule[2]
|
||||||
|
params = rule[3:]
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Rules[%d] [%s] error: format invalid", idx, line)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if _, ok := proxies[target]; !ok {
|
||||||
|
return nil, fmt.Errorf("Rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
||||||
|
}
|
||||||
|
|
||||||
rule = trimArr(rule)
|
rule = trimArr(rule)
|
||||||
|
params = trimArr(params)
|
||||||
|
var (
|
||||||
|
parseErr error
|
||||||
|
parsed C.Rule
|
||||||
|
)
|
||||||
|
|
||||||
switch rule[0] {
|
switch rule[0] {
|
||||||
case "DOMAIN":
|
case "DOMAIN":
|
||||||
rules = append(rules, R.NewDomain(rule[1], rule[2]))
|
parsed = R.NewDomain(payload, target)
|
||||||
case "DOMAIN-SUFFIX":
|
case "DOMAIN-SUFFIX":
|
||||||
rules = append(rules, R.NewDomainSuffix(rule[1], rule[2]))
|
parsed = R.NewDomainSuffix(payload, target)
|
||||||
case "DOMAIN-KEYWORD":
|
case "DOMAIN-KEYWORD":
|
||||||
rules = append(rules, R.NewDomainKeyword(rule[1], rule[2]))
|
parsed = R.NewDomainKeyword(payload, target)
|
||||||
case "GEOIP":
|
case "GEOIP":
|
||||||
rules = append(rules, R.NewGEOIP(rule[1], rule[2]))
|
noResolve := R.HasNoResolve(params)
|
||||||
|
parsed = R.NewGEOIP(payload, target, noResolve)
|
||||||
case "IP-CIDR", "IP-CIDR6":
|
case "IP-CIDR", "IP-CIDR6":
|
||||||
rules = append(rules, R.NewIPCIDR(rule[1], rule[2]))
|
noResolve := R.HasNoResolve(params)
|
||||||
|
parsed, parseErr = R.NewIPCIDR(payload, target, R.WithIPCIDRNoResolve(noResolve))
|
||||||
|
// deprecated when bump to 1.0
|
||||||
|
case "SOURCE-IP-CIDR":
|
||||||
|
fallthrough
|
||||||
|
case "SRC-IP-CIDR":
|
||||||
|
parsed, parseErr = R.NewIPCIDR(payload, target, R.WithIPCIDRSourceIP(true), R.WithIPCIDRNoResolve(true))
|
||||||
|
case "SRC-PORT":
|
||||||
|
parsed, parseErr = R.NewPort(payload, target, true)
|
||||||
|
case "DST-PORT":
|
||||||
|
parsed, parseErr = R.NewPort(payload, target, false)
|
||||||
|
case "MATCH":
|
||||||
|
fallthrough
|
||||||
|
// deprecated when bump to 1.0
|
||||||
case "FINAL":
|
case "FINAL":
|
||||||
rules = append(rules, R.NewFinal(rule[2]))
|
parsed = R.NewMatch(target)
|
||||||
|
default:
|
||||||
|
parseErr = fmt.Errorf("unsupported rule type %s", rule[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if parseErr != nil {
|
||||||
|
return nil, fmt.Errorf("Rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
rules = append(rules, parsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
return rules, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseHosts(cfg *RawConfig) (*trie.Trie, error) {
|
||||||
|
tree := trie.New()
|
||||||
|
if len(cfg.Hosts) != 0 {
|
||||||
|
for domain, ipStr := range cfg.Hosts {
|
||||||
|
ip := net.ParseIP(ipStr)
|
||||||
|
if ip == nil {
|
||||||
|
return nil, fmt.Errorf("%s is not a valid IP", ipStr)
|
||||||
|
}
|
||||||
|
tree.Insert(domain, ip)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
c.rules = rules
|
return tree, nil
|
||||||
c.event <- &Event{Type: "rules", Payload: rules}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) handleResponseMessage() {
|
func hostWithDefaultPort(host string, defPort string) (string, error) {
|
||||||
for elm := range c.reportCh {
|
if !strings.Contains(host, ":") {
|
||||||
event := elm.(*Event)
|
host += ":"
|
||||||
switch event.Type {
|
}
|
||||||
case "http-addr":
|
|
||||||
if event.Payload.(bool) == false {
|
hostname, port, err := net.SplitHostPort(host)
|
||||||
log.Errorf("Listening HTTP proxy at %d error", c.general.Port)
|
if err != nil {
|
||||||
c.general.Port = 0
|
return "", err
|
||||||
}
|
}
|
||||||
case "socks-addr":
|
|
||||||
if event.Payload.(bool) == false {
|
if port == "" {
|
||||||
log.Errorf("Listening SOCKS proxy at %d error", c.general.SocksPort)
|
port = defPort
|
||||||
c.general.SocksPort = 0
|
}
|
||||||
}
|
|
||||||
case "redir-addr":
|
return net.JoinHostPort(hostname, port), nil
|
||||||
if event.Payload.(bool) == false {
|
}
|
||||||
log.Errorf("Listening Redir proxy at %d error", c.general.RedirPort)
|
|
||||||
c.general.RedirPort = 0
|
func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
||||||
}
|
nameservers := []dns.NameServer{}
|
||||||
|
|
||||||
|
for idx, server := range servers {
|
||||||
|
// parse without scheme .e.g 8.8.8.8:53
|
||||||
|
if !strings.Contains(server, "://") {
|
||||||
|
server = "udp://" + server
|
||||||
|
}
|
||||||
|
u, err := url.Parse(server)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var addr, dnsNetType string
|
||||||
|
switch u.Scheme {
|
||||||
|
case "udp":
|
||||||
|
addr, err = hostWithDefaultPort(u.Host, "53")
|
||||||
|
dnsNetType = "" // UDP
|
||||||
|
case "tcp":
|
||||||
|
addr, err = hostWithDefaultPort(u.Host, "53")
|
||||||
|
dnsNetType = "tcp" // TCP
|
||||||
|
case "tls":
|
||||||
|
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||||
|
dnsNetType = "tcp-tls" // DNS over TLS
|
||||||
|
case "https":
|
||||||
|
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path}
|
||||||
|
addr = clearURL.String()
|
||||||
|
dnsNetType = "https" // DNS over HTTPS
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
nameservers = append(
|
||||||
|
nameservers,
|
||||||
|
dns.NameServer{
|
||||||
|
Net: dnsNetType,
|
||||||
|
Addr: addr,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return nameservers, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) {
|
||||||
|
ipNets := []*net.IPNet{}
|
||||||
|
|
||||||
|
for idx, ip := range ips {
|
||||||
|
_, ipnet, err := net.ParseCIDR(ip)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("DNS FallbackIP[%d] format error: %s", idx, err.Error())
|
||||||
|
}
|
||||||
|
ipNets = append(ipNets, ipnet)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ipNets, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseDNS(cfg RawDNS) (*DNS, error) {
|
||||||
|
if cfg.Enable && len(cfg.NameServer) == 0 {
|
||||||
|
return nil, fmt.Errorf("If DNS configuration is turned on, NameServer cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsCfg := &DNS{
|
||||||
|
Enable: cfg.Enable,
|
||||||
|
Listen: cfg.Listen,
|
||||||
|
IPv6: cfg.IPv6,
|
||||||
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
|
FallbackFilter: FallbackFilter{
|
||||||
|
IPCIDR: []*net.IPNet{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if dnsCfg.Fallback, err = parseNameServer(cfg.Fallback); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cfg.DefaultNameserver) == 0 {
|
||||||
|
return nil, errors.New("default nameserver should have at least one nameserver")
|
||||||
|
}
|
||||||
|
if dnsCfg.DefaultNameserver, err = parseNameServer(cfg.DefaultNameserver); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// check default nameserver is pure ip addr
|
||||||
|
for _, ns := range dnsCfg.DefaultNameserver {
|
||||||
|
host, _, err := net.SplitHostPort(ns.Addr)
|
||||||
|
if err != nil || net.ParseIP(host) == nil {
|
||||||
|
return nil, errors.New("default nameserver should be pure IP")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func newConfig() *Config {
|
if cfg.EnhancedMode == dns.FAKEIP {
|
||||||
event := make(chan interface{})
|
_, ipnet, err := net.ParseCIDR(cfg.FakeIPRange)
|
||||||
reportCh := make(chan interface{})
|
if err != nil {
|
||||||
config := &Config{
|
return nil, err
|
||||||
general: &General{},
|
}
|
||||||
proxies: make(map[string]C.Proxy),
|
|
||||||
rules: []C.Rule{},
|
|
||||||
lastUpdate: time.Now(),
|
|
||||||
|
|
||||||
event: event,
|
var host *trie.Trie
|
||||||
reportCh: reportCh,
|
// fake ip skip host filter
|
||||||
observable: observable.NewObservable(event),
|
if len(cfg.FakeIPFilter) != 0 {
|
||||||
|
host = trie.New()
|
||||||
|
for _, domain := range cfg.FakeIPFilter {
|
||||||
|
host.Insert(domain, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pool, err := fakeip.New(ipnet, 1000, host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsCfg.FakeIPRange = pool
|
||||||
}
|
}
|
||||||
go config.handleResponseMessage()
|
|
||||||
return config
|
dnsCfg.FallbackFilter.GeoIP = cfg.FallbackFilter.GeoIP
|
||||||
|
if fallbackip, err := parseFallbackIPCIDR(cfg.FallbackFilter.IPCIDR); err == nil {
|
||||||
|
dnsCfg.FallbackFilter.IPCIDR = fallbackip
|
||||||
|
}
|
||||||
|
|
||||||
|
return dnsCfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Instance return singleton instance of Config
|
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
||||||
func Instance() *Config {
|
users := make([]auth.AuthUser, 0)
|
||||||
once.Do(func() {
|
for _, line := range rawRecords {
|
||||||
config = newConfig()
|
userData := strings.SplitN(line, ":", 2)
|
||||||
})
|
if len(userData) == 2 {
|
||||||
return config
|
users = append(users, auth.AuthUser{User: userData[0], Pass: userData[1]})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return users
|
||||||
}
|
}
|
||||||
|
@ -1,79 +1,58 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/tar"
|
"fmt"
|
||||||
"compress/gzip"
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func downloadMMDB(path string) (err error) {
|
func downloadMMDB(path string) (err error) {
|
||||||
resp, err := http.Get("http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz")
|
resp, err := http.Get("https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
gr, err := gzip.NewReader(resp.Body)
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
defer gr.Close()
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
tr := tar.NewReader(gr)
|
return err
|
||||||
for {
|
|
||||||
h, err := tr.Next()
|
|
||||||
if err == io.EOF {
|
|
||||||
break
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.HasSuffix(h.Name, "GeoLite2-Country.mmdb") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
_, err = io.Copy(f, tr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init prepare necessary files
|
// Init prepare necessary files
|
||||||
func Init() {
|
func Init(dir string) error {
|
||||||
// initial homedir
|
// initial homedir
|
||||||
if _, err := os.Stat(C.Path.HomeDir()); os.IsNotExist(err) {
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
if err := os.MkdirAll(C.Path.HomeDir(), 0777); err != nil {
|
if err := os.MkdirAll(dir, 0777); err != nil {
|
||||||
log.Fatalf("Can't create config directory %s: %s", C.Path.HomeDir(), err.Error())
|
return fmt.Errorf("Can't create config directory %s: %s", dir, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// initial config.ini
|
// initial config.yaml
|
||||||
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
||||||
log.Info("Can't find config, create a empty file")
|
log.Infoln("Can't find config, create a initial config file")
|
||||||
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
f, err := os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Can't create file %s: %s", C.Path.Config(), err.Error())
|
||||||
|
}
|
||||||
|
f.Write([]byte(`port: 7890`))
|
||||||
|
f.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// initial mmdb
|
// initial mmdb
|
||||||
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||||
log.Info("Can't find MMDB, start download")
|
log.Infoln("Can't find MMDB, start download")
|
||||||
err := downloadMMDB(C.Path.MMDB())
|
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
||||||
if err != nil {
|
return fmt.Errorf("Can't download MMDB: %s", err.Error())
|
||||||
log.Fatalf("Can't download MMDB: %s", err.Error())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -1,31 +0,0 @@
|
|||||||
package config
|
|
||||||
|
|
||||||
type Mode int
|
|
||||||
|
|
||||||
var (
|
|
||||||
// ModeMapping is a mapping for Mode enum
|
|
||||||
ModeMapping = map[string]Mode{
|
|
||||||
"Global": Global,
|
|
||||||
"Rule": Rule,
|
|
||||||
"Direct": Direct,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
Global Mode = iota
|
|
||||||
Rule
|
|
||||||
Direct
|
|
||||||
)
|
|
||||||
|
|
||||||
func (m Mode) String() string {
|
|
||||||
switch m {
|
|
||||||
case Global:
|
|
||||||
return "Global"
|
|
||||||
case Rule:
|
|
||||||
return "Rule"
|
|
||||||
case Direct:
|
|
||||||
return "Direct"
|
|
||||||
default:
|
|
||||||
return "Unknow"
|
|
||||||
}
|
|
||||||
}
|
|
154
config/utils.go
154
config/utils.go
@ -4,7 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/Dreamacro/clash/adapters/outboundgroup"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
)
|
)
|
||||||
|
|
||||||
func trimArr(arr []string) (r []string) {
|
func trimArr(arr []string) (r []string) {
|
||||||
@ -14,25 +15,6 @@ func trimArr(arr []string) (r []string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func genAddr(port int, allowLan bool) string {
|
|
||||||
if allowLan {
|
|
||||||
return fmt.Sprintf(":%d", port)
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("127.0.0.1:%d", port)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|
||||||
var ps []C.Proxy
|
|
||||||
for _, name := range list {
|
|
||||||
p, ok := mapping[name]
|
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("'%s' not found", name)
|
|
||||||
}
|
|
||||||
ps = append(ps, p)
|
|
||||||
}
|
|
||||||
return ps, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func or(pointers ...*int) *int {
|
func or(pointers ...*int) *int {
|
||||||
for _, p := range pointers {
|
for _, p := range pointers {
|
||||||
if p != nil {
|
if p != nil {
|
||||||
@ -41,3 +23,135 @@ func or(pointers ...*int) *int {
|
|||||||
}
|
}
|
||||||
return pointers[len(pointers)-1]
|
return pointers[len(pointers)-1]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if ProxyGroups form DAG(Directed Acyclic Graph), and sort all ProxyGroups by dependency order.
|
||||||
|
// Meanwhile, record the original index in the config file.
|
||||||
|
// If loop is detected, return an error with location of loop.
|
||||||
|
func proxyGroupsDagSort(groupsConfig []map[string]interface{}) error {
|
||||||
|
type graphNode struct {
|
||||||
|
indegree int
|
||||||
|
// topological order
|
||||||
|
topo int
|
||||||
|
// the origional data in `groupsConfig`
|
||||||
|
data map[string]interface{}
|
||||||
|
// `outdegree` and `from` are used in loop locating
|
||||||
|
outdegree int
|
||||||
|
option *outboundgroup.GroupCommonOption
|
||||||
|
from []string
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
graph := make(map[string]*graphNode)
|
||||||
|
|
||||||
|
// Step 1.1 build dependency graph
|
||||||
|
for _, mapping := range groupsConfig {
|
||||||
|
option := &outboundgroup.GroupCommonOption{}
|
||||||
|
if err := decoder.Decode(mapping, option); err != nil {
|
||||||
|
return fmt.Errorf("ProxyGroup %s: %s", option.Name, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
groupName := option.Name
|
||||||
|
if node, ok := graph[groupName]; ok {
|
||||||
|
if node.data != nil {
|
||||||
|
return fmt.Errorf("ProxyGroup %s: duplicate group name", groupName)
|
||||||
|
}
|
||||||
|
node.data = mapping
|
||||||
|
node.option = option
|
||||||
|
} else {
|
||||||
|
graph[groupName] = &graphNode{0, -1, mapping, 0, option, nil}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range option.Proxies {
|
||||||
|
if node, ex := graph[proxy]; ex {
|
||||||
|
node.indegree++
|
||||||
|
} else {
|
||||||
|
graph[proxy] = &graphNode{1, -1, nil, 0, nil, nil}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Step 1.2 Topological Sort
|
||||||
|
// topological index of **ProxyGroup**
|
||||||
|
index := 0
|
||||||
|
queue := make([]string, 0)
|
||||||
|
for name, node := range graph {
|
||||||
|
// in the begning, put nodes that have `node.indegree == 0` into queue.
|
||||||
|
if node.indegree == 0 {
|
||||||
|
queue = append(queue, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// every element in queue have indegree == 0
|
||||||
|
for ; len(queue) > 0; queue = queue[1:] {
|
||||||
|
name := queue[0]
|
||||||
|
node := graph[name]
|
||||||
|
if node.option != nil {
|
||||||
|
index++
|
||||||
|
groupsConfig[len(groupsConfig)-index] = node.data
|
||||||
|
if len(node.option.Proxies) == 0 {
|
||||||
|
delete(graph, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range node.option.Proxies {
|
||||||
|
child := graph[proxy]
|
||||||
|
child.indegree--
|
||||||
|
if child.indegree == 0 {
|
||||||
|
queue = append(queue, proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete(graph, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// no loop is detected, return sorted ProxyGroup
|
||||||
|
if len(graph) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// if loop is detected, locate the loop and throw an error
|
||||||
|
// Step 2.1 rebuild the graph, fill `outdegree` and `from` filed
|
||||||
|
for name, node := range graph {
|
||||||
|
if node.option == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(node.option.Proxies) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range node.option.Proxies {
|
||||||
|
node.outdegree++
|
||||||
|
child := graph[proxy]
|
||||||
|
if child.from == nil {
|
||||||
|
child.from = make([]string, 0, child.indegree)
|
||||||
|
}
|
||||||
|
child.from = append(child.from, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Step 2.2 remove nodes outside the loop. so that we have only the loops remain in `graph`
|
||||||
|
queue = make([]string, 0)
|
||||||
|
// initialize queue with node have outdegree == 0
|
||||||
|
for name, node := range graph {
|
||||||
|
if node.outdegree == 0 {
|
||||||
|
queue = append(queue, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// every element in queue have outdegree == 0
|
||||||
|
for ; len(queue) > 0; queue = queue[1:] {
|
||||||
|
name := queue[0]
|
||||||
|
node := graph[name]
|
||||||
|
for _, f := range node.from {
|
||||||
|
graph[f].outdegree--
|
||||||
|
if graph[f].outdegree == 0 {
|
||||||
|
queue = append(queue, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete(graph, name)
|
||||||
|
}
|
||||||
|
// Step 2.3 report the elements in loop
|
||||||
|
loopElements := make([]string, 0, len(graph))
|
||||||
|
for name := range graph {
|
||||||
|
loopElements = append(loopElements, name)
|
||||||
|
delete(graph, name)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("Loop is detected in ProxyGroup, please check following ProxyGroups: %v", loopElements)
|
||||||
|
}
|
||||||
|
@ -1,35 +1,88 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Adapter Type
|
// Adapter Type
|
||||||
const (
|
const (
|
||||||
Direct AdapterType = iota
|
Direct AdapterType = iota
|
||||||
Fallback
|
|
||||||
Reject
|
Reject
|
||||||
Selector
|
|
||||||
Shadowsocks
|
Shadowsocks
|
||||||
|
Snell
|
||||||
Socks5
|
Socks5
|
||||||
URLTest
|
Http
|
||||||
Vmess
|
Vmess
|
||||||
|
Trojan
|
||||||
|
|
||||||
|
Relay
|
||||||
|
Selector
|
||||||
|
Fallback
|
||||||
|
URLTest
|
||||||
|
LoadBalance
|
||||||
)
|
)
|
||||||
|
|
||||||
type ProxyAdapter interface {
|
type ServerAdapter interface {
|
||||||
Conn() net.Conn
|
net.Conn
|
||||||
Close()
|
Metadata() *Metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServerAdapter interface {
|
type Connection interface {
|
||||||
Metadata() *Metadata
|
Chains() Chain
|
||||||
Close()
|
AppendToChains(adapter ProxyAdapter)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Chain []string
|
||||||
|
|
||||||
|
func (c Chain) String() string {
|
||||||
|
switch len(c) {
|
||||||
|
case 0:
|
||||||
|
return ""
|
||||||
|
case 1:
|
||||||
|
return c[0]
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("%s[%s]", c[len(c)-1], c[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Conn interface {
|
||||||
|
net.Conn
|
||||||
|
Connection
|
||||||
|
}
|
||||||
|
|
||||||
|
type PacketConn interface {
|
||||||
|
net.PacketConn
|
||||||
|
Connection
|
||||||
|
WriteWithMetadata(p []byte, metadata *Metadata) (n int, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyAdapter interface {
|
||||||
|
Name() string
|
||||||
|
Type() AdapterType
|
||||||
|
StreamConn(c net.Conn, metadata *Metadata) (net.Conn, error)
|
||||||
|
DialContext(ctx context.Context, metadata *Metadata) (Conn, error)
|
||||||
|
DialUDP(metadata *Metadata) (PacketConn, error)
|
||||||
|
SupportUDP() bool
|
||||||
|
MarshalJSON() ([]byte, error)
|
||||||
|
Addr() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type DelayHistory struct {
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Delay uint16 `json:"delay"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Proxy interface {
|
type Proxy interface {
|
||||||
Name() string
|
ProxyAdapter
|
||||||
Type() AdapterType
|
Alive() bool
|
||||||
Generator(metadata *Metadata) (ProxyAdapter, error)
|
DelayHistory() []DelayHistory
|
||||||
|
Dial(metadata *Metadata) (Conn, error)
|
||||||
|
LastDelay() uint16
|
||||||
|
URLTest(ctx context.Context, url string) (uint16, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdapterType is enum of adapter type
|
// AdapterType is enum of adapter type
|
||||||
@ -39,21 +92,52 @@ func (at AdapterType) String() string {
|
|||||||
switch at {
|
switch at {
|
||||||
case Direct:
|
case Direct:
|
||||||
return "Direct"
|
return "Direct"
|
||||||
case Fallback:
|
|
||||||
return "Fallback"
|
|
||||||
case Reject:
|
case Reject:
|
||||||
return "Reject"
|
return "Reject"
|
||||||
case Selector:
|
|
||||||
return "Selector"
|
|
||||||
case Shadowsocks:
|
case Shadowsocks:
|
||||||
return "Shadowsocks"
|
return "Shadowsocks"
|
||||||
|
case Snell:
|
||||||
|
return "Snell"
|
||||||
case Socks5:
|
case Socks5:
|
||||||
return "Socks5"
|
return "Socks5"
|
||||||
case URLTest:
|
case Http:
|
||||||
return "URLTest"
|
return "Http"
|
||||||
case Vmess:
|
case Vmess:
|
||||||
return "Vmess"
|
return "Vmess"
|
||||||
|
case Trojan:
|
||||||
|
return "Trojan"
|
||||||
|
|
||||||
|
case Relay:
|
||||||
|
return "Relay"
|
||||||
|
case Selector:
|
||||||
|
return "Selector"
|
||||||
|
case Fallback:
|
||||||
|
return "Fallback"
|
||||||
|
case URLTest:
|
||||||
|
return "URLTest"
|
||||||
|
case LoadBalance:
|
||||||
|
return "LoadBalance"
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return "Unknow"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UDPPacket contains the data of UDP packet, and offers control/info of UDP packet's source
|
||||||
|
type UDPPacket interface {
|
||||||
|
// Data get the payload of UDP Packet
|
||||||
|
Data() []byte
|
||||||
|
|
||||||
|
// WriteBack writes the payload with source IP/Port equals addr
|
||||||
|
// - variable source IP/Port is important to STUN
|
||||||
|
// - if addr is not provided, WriteBack will wirte out UDP packet with SourceIP/Prot equals to origional Target,
|
||||||
|
// this is important when using Fake-IP.
|
||||||
|
WriteBack(b []byte, addr net.Addr) (n int, err error)
|
||||||
|
|
||||||
|
// Close closes the underlaying connection.
|
||||||
|
Close() error
|
||||||
|
|
||||||
|
// LocalAddr returns the source IP/Port of packet
|
||||||
|
LocalAddr() net.Addr
|
||||||
|
}
|
||||||
|
@ -1,10 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
type General struct {
|
|
||||||
Mode *string `json:"mode,omitempty"`
|
|
||||||
AllowLan *bool `json:"allow-lan,omitempty"`
|
|
||||||
Port *int `json:"port,omitempty"`
|
|
||||||
SocksPort *int `json:"socks-port,omitempty"`
|
|
||||||
RedirPort *int `json:"redir-port,omitempty"`
|
|
||||||
LogLevel *string `json:"log-level,omitempty"`
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
var (
|
|
||||||
// LogLevelMapping is a mapping for LogLevel enum
|
|
||||||
LogLevelMapping = map[string]LogLevel{
|
|
||||||
"error": ERROR,
|
|
||||||
"warning": WARNING,
|
|
||||||
"info": INFO,
|
|
||||||
"debug": DEBUG,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
ERROR LogLevel = iota
|
|
||||||
WARNING
|
|
||||||
INFO
|
|
||||||
DEBUG
|
|
||||||
)
|
|
||||||
|
|
||||||
type LogLevel int
|
|
||||||
|
|
||||||
func (l LogLevel) String() string {
|
|
||||||
switch l {
|
|
||||||
case INFO:
|
|
||||||
return "info"
|
|
||||||
case WARNING:
|
|
||||||
return "warning"
|
|
||||||
case ERROR:
|
|
||||||
return "error"
|
|
||||||
case DEBUG:
|
|
||||||
return "debug"
|
|
||||||
default:
|
|
||||||
return "unknow"
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,7 +1,9 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"net"
|
"net"
|
||||||
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Socks addr type
|
// Socks addr type
|
||||||
@ -13,8 +15,10 @@ const (
|
|||||||
TCP NetWork = iota
|
TCP NetWork = iota
|
||||||
UDP
|
UDP
|
||||||
|
|
||||||
HTTP SourceType = iota
|
HTTP Type = iota
|
||||||
|
HTTPCONNECT
|
||||||
SOCKS
|
SOCKS
|
||||||
|
REDIR
|
||||||
)
|
)
|
||||||
|
|
||||||
type NetWork int
|
type NetWork int
|
||||||
@ -26,21 +30,76 @@ func (n *NetWork) String() string {
|
|||||||
return "udp"
|
return "udp"
|
||||||
}
|
}
|
||||||
|
|
||||||
type SourceType int
|
func (n NetWork) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(n.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
type Type int
|
||||||
|
|
||||||
|
func (t Type) String() string {
|
||||||
|
switch t {
|
||||||
|
case HTTP:
|
||||||
|
return "HTTP"
|
||||||
|
case HTTPCONNECT:
|
||||||
|
return "HTTP Connect"
|
||||||
|
case SOCKS:
|
||||||
|
return "Socks5"
|
||||||
|
case REDIR:
|
||||||
|
return "Redir"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t Type) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(t.String())
|
||||||
|
}
|
||||||
|
|
||||||
// Metadata is used to store connection address
|
// Metadata is used to store connection address
|
||||||
type Metadata struct {
|
type Metadata struct {
|
||||||
NetWork NetWork
|
NetWork NetWork `json:"network"`
|
||||||
Source SourceType
|
Type Type `json:"type"`
|
||||||
AddrType int
|
SrcIP net.IP `json:"sourceIP"`
|
||||||
Host string
|
DstIP net.IP `json:"destinationIP"`
|
||||||
IP *net.IP
|
SrcPort string `json:"sourcePort"`
|
||||||
Port string
|
DstPort string `json:"destinationPort"`
|
||||||
|
AddrType int `json:"-"`
|
||||||
|
Host string `json:"host"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (addr *Metadata) String() string {
|
func (m *Metadata) RemoteAddress() string {
|
||||||
if addr.Host == "" {
|
return net.JoinHostPort(m.String(), m.DstPort)
|
||||||
return addr.IP.String()
|
}
|
||||||
}
|
|
||||||
return addr.Host
|
func (m *Metadata) SourceAddress() string {
|
||||||
|
return net.JoinHostPort(m.SrcIP.String(), m.SrcPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Metadata) Resolved() bool {
|
||||||
|
return m.DstIP != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Metadata) UDPAddr() *net.UDPAddr {
|
||||||
|
if m.NetWork != UDP || m.DstIP == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
port, _ := strconv.Atoi(m.DstPort)
|
||||||
|
return &net.UDPAddr{
|
||||||
|
IP: m.DstIP,
|
||||||
|
Port: port,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Metadata) String() string {
|
||||||
|
if m.Host != "" {
|
||||||
|
return m.Host
|
||||||
|
} else if m.DstIP != nil {
|
||||||
|
return m.DstIP.String()
|
||||||
|
} else {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Metadata) Valid() bool {
|
||||||
|
return m.Host != "" || m.DstIP != nil
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,8 @@ package constant
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"os/user"
|
|
||||||
P "path"
|
P "path"
|
||||||
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
const Name = "clash"
|
const Name = "clash"
|
||||||
@ -12,38 +12,47 @@ const Name = "clash"
|
|||||||
var Path *path
|
var Path *path
|
||||||
|
|
||||||
type path struct {
|
type path struct {
|
||||||
homedir string
|
homeDir string
|
||||||
|
configFile string
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
currentUser, err := user.Current()
|
homeDir, err := os.UserHomeDir()
|
||||||
var homedir string
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
dir := os.Getenv("HOME")
|
homeDir, _ = os.Getwd()
|
||||||
if dir == "" {
|
|
||||||
dir, _ = os.Getwd()
|
|
||||||
}
|
|
||||||
homedir = dir
|
|
||||||
} else {
|
|
||||||
homedir = currentUser.HomeDir
|
|
||||||
}
|
}
|
||||||
homedir = P.Join(homedir, ".config", Name)
|
|
||||||
Path = &path{homedir: homedir}
|
homeDir = P.Join(homeDir, ".config", Name)
|
||||||
|
Path = &path{homeDir: homeDir, configFile: "config.yaml"}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetHomeDir is used to set the configuration path
|
// SetHomeDir is used to set the configuration path
|
||||||
func SetHomeDir(root string) {
|
func SetHomeDir(root string) {
|
||||||
Path = &path{homedir: root}
|
Path.homeDir = root
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConfig is used to set the configuration file
|
||||||
|
func SetConfig(file string) {
|
||||||
|
Path.configFile = file
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) HomeDir() string {
|
func (p *path) HomeDir() string {
|
||||||
return p.homedir
|
return p.homeDir
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) Config() string {
|
func (p *path) Config() string {
|
||||||
return P.Join(p.homedir, "config.yml")
|
return p.configFile
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve return a absolute path or a relative path with homedir
|
||||||
|
func (p *path) Resolve(path string) string {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return filepath.Join(p.HomeDir(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
return path
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) MMDB() string {
|
func (p *path) MMDB() string {
|
||||||
return P.Join(p.homedir, "Country.mmdb")
|
return P.Join(p.homeDir, "Country.mmdb")
|
||||||
}
|
}
|
||||||
|
@ -1,7 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
// ProxySignal is used to handle graceful shutdown of proxy
|
|
||||||
type ProxySignal struct {
|
|
||||||
Done chan<- struct{}
|
|
||||||
Closed <-chan struct{}
|
|
||||||
}
|
|
@ -7,7 +7,10 @@ const (
|
|||||||
DomainKeyword
|
DomainKeyword
|
||||||
GEOIP
|
GEOIP
|
||||||
IPCIDR
|
IPCIDR
|
||||||
FINAL
|
SrcIPCIDR
|
||||||
|
SrcPort
|
||||||
|
DstPort
|
||||||
|
MATCH
|
||||||
)
|
)
|
||||||
|
|
||||||
type RuleType int
|
type RuleType int
|
||||||
@ -21,19 +24,26 @@ func (rt RuleType) String() string {
|
|||||||
case DomainKeyword:
|
case DomainKeyword:
|
||||||
return "DomainKeyword"
|
return "DomainKeyword"
|
||||||
case GEOIP:
|
case GEOIP:
|
||||||
return "GEOIP"
|
return "GeoIP"
|
||||||
case IPCIDR:
|
case IPCIDR:
|
||||||
return "IPCIDR"
|
return "IPCIDR"
|
||||||
case FINAL:
|
case SrcIPCIDR:
|
||||||
return "FINAL"
|
return "SrcIPCIDR"
|
||||||
|
case SrcPort:
|
||||||
|
return "SrcPort"
|
||||||
|
case DstPort:
|
||||||
|
return "DstPort"
|
||||||
|
case MATCH:
|
||||||
|
return "Match"
|
||||||
default:
|
default:
|
||||||
return "Unknow"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Rule interface {
|
type Rule interface {
|
||||||
RuleType() RuleType
|
RuleType() RuleType
|
||||||
IsMatch(metadata *Metadata) bool
|
Match(metadata *Metadata) bool
|
||||||
Adapter() string
|
Adapter() string
|
||||||
Payload() string
|
Payload() string
|
||||||
|
NoResolveIP() bool
|
||||||
}
|
}
|
||||||
|
@ -1,55 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Traffic struct {
|
|
||||||
up chan int64
|
|
||||||
down chan int64
|
|
||||||
upCount int64
|
|
||||||
downCount int64
|
|
||||||
upTotal int64
|
|
||||||
downTotal int64
|
|
||||||
interval time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) Up() chan<- int64 {
|
|
||||||
return t.up
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) Down() chan<- int64 {
|
|
||||||
return t.down
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) Now() (up int64, down int64) {
|
|
||||||
return t.upTotal, t.downTotal
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) handle() {
|
|
||||||
go t.handleCh(t.up, &t.upCount, &t.upTotal)
|
|
||||||
go t.handleCh(t.down, &t.downCount, &t.downTotal)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) handleCh(ch <-chan int64, count *int64, total *int64) {
|
|
||||||
ticker := time.NewTicker(t.interval)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case n := <-ch:
|
|
||||||
*count += n
|
|
||||||
case <-ticker.C:
|
|
||||||
*total = *count
|
|
||||||
*count = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTraffic(interval time.Duration) *Traffic {
|
|
||||||
t := &Traffic{
|
|
||||||
up: make(chan int64),
|
|
||||||
down: make(chan int64),
|
|
||||||
interval: interval,
|
|
||||||
}
|
|
||||||
go t.handle()
|
|
||||||
return t
|
|
||||||
}
|
|
6
constant/version.go
Normal file
6
constant/version.go
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
package constant
|
||||||
|
|
||||||
|
var (
|
||||||
|
Version = "unknown version"
|
||||||
|
BuildTime = "unknown time"
|
||||||
|
)
|
66
dns/client.go
Normal file
66
dns/client.go
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
type client struct {
|
||||||
|
*D.Client
|
||||||
|
r *Resolver
|
||||||
|
port string
|
||||||
|
host string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
return c.ExchangeContext(context.Background(), m)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
var ip net.IP
|
||||||
|
if c.r == nil {
|
||||||
|
// a default ip dns
|
||||||
|
ip = net.ParseIP(c.host)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if ip, err = c.r.ResolveIP(c.host); err != nil {
|
||||||
|
return nil, fmt.Errorf("use default dns resolve failed: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
d := dialer.Dialer()
|
||||||
|
if dialer.DialHook != nil {
|
||||||
|
network := "udp"
|
||||||
|
if strings.HasPrefix(c.Client.Net, "tcp") {
|
||||||
|
network = "tcp"
|
||||||
|
}
|
||||||
|
dialer.DialHook(d, network, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Client.Dialer = d
|
||||||
|
|
||||||
|
// miekg/dns ExchangeContext doesn't respond to context cancel.
|
||||||
|
// this is a workaround
|
||||||
|
type result struct {
|
||||||
|
msg *D.Msg
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
ch := make(chan result, 1)
|
||||||
|
go func() {
|
||||||
|
msg, _, err := c.Client.Exchange(m, net.JoinHostPort(ip.String(), c.port))
|
||||||
|
ch <- result{msg, err}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case ret := <-ch:
|
||||||
|
return ret.msg, ret.err
|
||||||
|
}
|
||||||
|
}
|
94
dns/doh.go
Normal file
94
dns/doh.go
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// dotMimeType is the DoH mimetype that should be used.
|
||||||
|
dotMimeType = "application/dns-message"
|
||||||
|
)
|
||||||
|
|
||||||
|
type dohClient struct {
|
||||||
|
url string
|
||||||
|
transport *http.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dc *dohClient) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
return dc.ExchangeContext(context.Background(), m)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dc *dohClient) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
req, err := dc.newRequest(m)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
return dc.doRequest(req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRequest returns a new DoH request given a dns.Msg.
|
||||||
|
func (dc *dohClient) newRequest(m *D.Msg) (*http.Request, error) {
|
||||||
|
buf, err := m.Pack()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodPost, dc.url+"?bla=foo:443", bytes.NewReader(buf))
|
||||||
|
if err != nil {
|
||||||
|
return req, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("content-type", dotMimeType)
|
||||||
|
req.Header.Set("accept", dotMimeType)
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dc *dohClient) doRequest(req *http.Request) (msg *D.Msg, err error) {
|
||||||
|
client := &http.Client{Transport: dc.transport}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
buf, err := ioutil.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
msg = &D.Msg{}
|
||||||
|
err = msg.Unpack(buf)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDoHClient(url string, r *Resolver) *dohClient {
|
||||||
|
return &dohClient{
|
||||||
|
url: url,
|
||||||
|
transport: &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{ClientSessionCache: globalSessionCache},
|
||||||
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := r.ResolveIPv4(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialer.DialContext(ctx, "tcp4", net.JoinHostPort(ip.String(), port))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
26
dns/filters.go
Normal file
26
dns/filters.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/mmdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fallbackFilter interface {
|
||||||
|
Match(net.IP) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type geoipFilter struct{}
|
||||||
|
|
||||||
|
func (gf *geoipFilter) Match(ip net.IP) bool {
|
||||||
|
record, _ := mmdb.Instance().Country(ip)
|
||||||
|
return record.Country.IsoCode != "CN" && record.Country.IsoCode != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
type ipnetFilter struct {
|
||||||
|
ipnet *net.IPNet
|
||||||
|
}
|
||||||
|
|
||||||
|
func (inf *ipnetFilter) Match(ip net.IP) bool {
|
||||||
|
return inf.ipnet.Contains(ip)
|
||||||
|
}
|
85
dns/middleware.go
Normal file
85
dns/middleware.go
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/fakeip"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
type handler func(w D.ResponseWriter, r *D.Msg)
|
||||||
|
type middleware func(next handler) handler
|
||||||
|
|
||||||
|
func withFakeIP(fakePool *fakeip.Pool) middleware {
|
||||||
|
return func(next handler) handler {
|
||||||
|
return func(w D.ResponseWriter, r *D.Msg) {
|
||||||
|
q := r.Question[0]
|
||||||
|
|
||||||
|
if q.Qtype == D.TypeAAAA {
|
||||||
|
D.HandleFailed(w, r)
|
||||||
|
return
|
||||||
|
} else if q.Qtype != D.TypeA {
|
||||||
|
next(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
host := strings.TrimRight(q.Name, ".")
|
||||||
|
if fakePool.LookupHost(host) {
|
||||||
|
next(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rr := &D.A{}
|
||||||
|
rr.Hdr = D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: dnsDefaultTTL}
|
||||||
|
ip := fakePool.Lookup(host)
|
||||||
|
rr.A = ip
|
||||||
|
msg := r.Copy()
|
||||||
|
msg.Answer = []D.RR{rr}
|
||||||
|
|
||||||
|
setMsgTTL(msg, 1)
|
||||||
|
msg.SetRcode(r, msg.Rcode)
|
||||||
|
msg.Authoritative = true
|
||||||
|
w.WriteMsg(msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func withResolver(resolver *Resolver) handler {
|
||||||
|
return func(w D.ResponseWriter, r *D.Msg) {
|
||||||
|
msg, err := resolver.Exchange(r)
|
||||||
|
if err != nil {
|
||||||
|
q := r.Question[0]
|
||||||
|
log.Debugln("[DNS Server] Exchange %s failed: %v", q.String(), err)
|
||||||
|
D.HandleFailed(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msg.SetRcode(r, msg.Rcode)
|
||||||
|
msg.Authoritative = true
|
||||||
|
w.WriteMsg(msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func compose(middlewares []middleware, endpoint handler) handler {
|
||||||
|
length := len(middlewares)
|
||||||
|
h := endpoint
|
||||||
|
for i := length - 1; i >= 0; i-- {
|
||||||
|
middleware := middlewares[i]
|
||||||
|
h = middleware(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHandler(resolver *Resolver) handler {
|
||||||
|
middlewares := []middleware{}
|
||||||
|
|
||||||
|
if resolver.FakeIPEnabled() {
|
||||||
|
middlewares = append(middlewares, withFakeIP(resolver.pool))
|
||||||
|
}
|
||||||
|
|
||||||
|
return compose(middlewares, withResolver(resolver))
|
||||||
|
}
|
316
dns/resolver.go
Normal file
316
dns/resolver.go
Normal file
@ -0,0 +1,316 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/common/picker"
|
||||||
|
"github.com/Dreamacro/clash/component/fakeip"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
"golang.org/x/sync/singleflight"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalSessionCache = tls.NewLRUClientSessionCache(64)
|
||||||
|
)
|
||||||
|
|
||||||
|
type dnsClient interface {
|
||||||
|
Exchange(m *D.Msg) (msg *D.Msg, err error)
|
||||||
|
ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
Msg *D.Msg
|
||||||
|
Error error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Resolver struct {
|
||||||
|
ipv6 bool
|
||||||
|
mapping bool
|
||||||
|
fakeip bool
|
||||||
|
pool *fakeip.Pool
|
||||||
|
main []dnsClient
|
||||||
|
fallback []dnsClient
|
||||||
|
fallbackFilters []fallbackFilter
|
||||||
|
group singleflight.Group
|
||||||
|
cache *cache.Cache
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIP request with TypeA and TypeAAAA, priority return TypeA
|
||||||
|
func (r *Resolver) ResolveIP(host string) (ip net.IP, err error) {
|
||||||
|
ch := make(chan net.IP, 1)
|
||||||
|
go func() {
|
||||||
|
defer close(ch)
|
||||||
|
ip, err := r.resolveIP(host, D.TypeAAAA)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch <- ip
|
||||||
|
}()
|
||||||
|
|
||||||
|
ip, err = r.resolveIP(host, D.TypeA)
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, open := <-ch
|
||||||
|
if !open {
|
||||||
|
return nil, resolver.ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return ip, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIPv4 request with TypeA
|
||||||
|
func (r *Resolver) ResolveIPv4(host string) (ip net.IP, err error) {
|
||||||
|
return r.resolveIP(host, D.TypeA)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIPv6 request with TypeAAAA
|
||||||
|
func (r *Resolver) ResolveIPv6(host string) (ip net.IP, err error) {
|
||||||
|
return r.resolveIP(host, D.TypeAAAA)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) shouldFallback(ip net.IP) bool {
|
||||||
|
for _, filter := range r.fallbackFilters {
|
||||||
|
if filter.Match(ip) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange a batch of dns request, and it use cache
|
||||||
|
func (r *Resolver) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
if len(m.Question) == 0 {
|
||||||
|
return nil, errors.New("should have one question at least")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := m.Question[0]
|
||||||
|
cache, expireTime := r.cache.GetWithExpire(q.String())
|
||||||
|
if cache != nil {
|
||||||
|
msg = cache.(*D.Msg).Copy()
|
||||||
|
setMsgTTL(msg, uint32(expireTime.Sub(time.Now()).Seconds()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if msg == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
putMsgToCache(r.cache, q.String(), msg)
|
||||||
|
if r.mapping {
|
||||||
|
ips := r.msgToIP(msg)
|
||||||
|
for _, ip := range ips {
|
||||||
|
putMsgToCache(r.cache, ip.String(), msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
ret, err, _ := r.group.Do(q.String(), func() (interface{}, error) {
|
||||||
|
isIPReq := isIPRequest(q)
|
||||||
|
if isIPReq {
|
||||||
|
return r.fallbackExchange(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.batchExchange(r.main, m)
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
msg = ret.(*D.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// IPToHost return fake-ip or redir-host mapping host
|
||||||
|
func (r *Resolver) IPToHost(ip net.IP) (string, bool) {
|
||||||
|
if r.fakeip {
|
||||||
|
return r.pool.LookBack(ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
cache := r.cache.Get(ip.String())
|
||||||
|
if cache == nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
fqdn := cache.(*D.Msg).Question[0].Name
|
||||||
|
return strings.TrimRight(fqdn, "."), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) IsMapping() bool {
|
||||||
|
return r.mapping
|
||||||
|
}
|
||||||
|
|
||||||
|
// FakeIPEnabled returns if fake-ip is enabled
|
||||||
|
func (r *Resolver) FakeIPEnabled() bool {
|
||||||
|
return r.fakeip
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsFakeIP determine if given ip is a fake-ip
|
||||||
|
func (r *Resolver) IsFakeIP(ip net.IP) bool {
|
||||||
|
if r.FakeIPEnabled() {
|
||||||
|
return r.pool.Exist(ip)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) batchExchange(clients []dnsClient, m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
fast, ctx := picker.WithTimeout(context.Background(), time.Second*5)
|
||||||
|
for _, client := range clients {
|
||||||
|
r := client
|
||||||
|
fast.Go(func() (interface{}, error) {
|
||||||
|
m, err := r.ExchangeContext(ctx, m)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if m.Rcode == D.RcodeServerFailure || m.Rcode == D.RcodeRefused {
|
||||||
|
return nil, errors.New("server failure")
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
elm := fast.Wait()
|
||||||
|
if elm == nil {
|
||||||
|
return nil, errors.New("All DNS requests failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
msg = elm.(*D.Msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) fallbackExchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
msgCh := r.asyncExchange(r.main, m)
|
||||||
|
if r.fallback == nil {
|
||||||
|
res := <-msgCh
|
||||||
|
msg, err = res.Msg, res.Error
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fallbackMsg := r.asyncExchange(r.fallback, m)
|
||||||
|
res := <-msgCh
|
||||||
|
if res.Error == nil {
|
||||||
|
if ips := r.msgToIP(res.Msg); len(ips) != 0 {
|
||||||
|
if !r.shouldFallback(ips[0]) {
|
||||||
|
msg = res.Msg
|
||||||
|
err = res.Error
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res = <-fallbackMsg
|
||||||
|
msg, err = res.Msg, res.Error
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) resolveIP(host string, dnsType uint16) (ip net.IP, err error) {
|
||||||
|
ip = net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
isIPv4 := ip.To4() != nil
|
||||||
|
if dnsType == D.TypeAAAA && !isIPv4 {
|
||||||
|
return ip, nil
|
||||||
|
} else if dnsType == D.TypeA && isIPv4 {
|
||||||
|
return ip, nil
|
||||||
|
} else {
|
||||||
|
return nil, resolver.ErrIPVersion
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
query := &D.Msg{}
|
||||||
|
query.SetQuestion(D.Fqdn(host), dnsType)
|
||||||
|
|
||||||
|
msg, err := r.Exchange(query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ips := r.msgToIP(msg)
|
||||||
|
ipLength := len(ips)
|
||||||
|
if ipLength == 0 {
|
||||||
|
return nil, resolver.ErrIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
ip = ips[rand.Intn(ipLength)]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) msgToIP(msg *D.Msg) []net.IP {
|
||||||
|
ips := []net.IP{}
|
||||||
|
|
||||||
|
for _, answer := range msg.Answer {
|
||||||
|
switch ans := answer.(type) {
|
||||||
|
case *D.AAAA:
|
||||||
|
ips = append(ips, ans.AAAA)
|
||||||
|
case *D.A:
|
||||||
|
ips = append(ips, ans.A)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ips
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) asyncExchange(client []dnsClient, msg *D.Msg) <-chan *result {
|
||||||
|
ch := make(chan *result, 1)
|
||||||
|
go func() {
|
||||||
|
res, err := r.batchExchange(client, msg)
|
||||||
|
ch <- &result{Msg: res, Error: err}
|
||||||
|
}()
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
type NameServer struct {
|
||||||
|
Net string
|
||||||
|
Addr string
|
||||||
|
}
|
||||||
|
|
||||||
|
type FallbackFilter struct {
|
||||||
|
GeoIP bool
|
||||||
|
IPCIDR []*net.IPNet
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Main, Fallback []NameServer
|
||||||
|
Default []NameServer
|
||||||
|
IPv6 bool
|
||||||
|
EnhancedMode EnhancedMode
|
||||||
|
FallbackFilter FallbackFilter
|
||||||
|
Pool *fakeip.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(config Config) *Resolver {
|
||||||
|
defaultResolver := &Resolver{
|
||||||
|
main: transform(config.Default, nil),
|
||||||
|
cache: cache.New(time.Second * 60),
|
||||||
|
}
|
||||||
|
|
||||||
|
r := &Resolver{
|
||||||
|
ipv6: config.IPv6,
|
||||||
|
main: transform(config.Main, defaultResolver),
|
||||||
|
cache: cache.New(time.Second * 60),
|
||||||
|
mapping: config.EnhancedMode == MAPPING,
|
||||||
|
fakeip: config.EnhancedMode == FAKEIP,
|
||||||
|
pool: config.Pool,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(config.Fallback) != 0 {
|
||||||
|
r.fallback = transform(config.Fallback, defaultResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
fallbackFilters := []fallbackFilter{}
|
||||||
|
if config.FallbackFilter.GeoIP {
|
||||||
|
fallbackFilters = append(fallbackFilters, &geoipFilter{})
|
||||||
|
}
|
||||||
|
for _, ipnet := range config.FallbackFilter.IPCIDR {
|
||||||
|
fallbackFilters = append(fallbackFilters, &ipnetFilter{ipnet: ipnet})
|
||||||
|
}
|
||||||
|
r.fallbackFilters = fallbackFilters
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
70
dns/server.go
Normal file
70
dns/server.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
address string
|
||||||
|
server = &Server{}
|
||||||
|
|
||||||
|
dnsDefaultTTL uint32 = 600
|
||||||
|
)
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
*D.Server
|
||||||
|
handler handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
|
||||||
|
if len(r.Question) == 0 {
|
||||||
|
D.HandleFailed(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.handler(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) setHandler(handler handler) {
|
||||||
|
s.handler = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReCreateServer(addr string, resolver *Resolver) error {
|
||||||
|
if addr == address && resolver != nil {
|
||||||
|
handler := newHandler(resolver)
|
||||||
|
server.setHandler(handler)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if server.Server != nil {
|
||||||
|
server.Shutdown()
|
||||||
|
address = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
_, port, err := net.SplitHostPort(addr)
|
||||||
|
if port == "0" || port == "" || err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
p, err := net.ListenUDP("udp", udpAddr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
address = addr
|
||||||
|
handler := newHandler(resolver)
|
||||||
|
server = &Server{handler: handler}
|
||||||
|
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
server.ActivateAndServe()
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user