Compare commits
160 Commits
Author | SHA1 | Date | |
---|---|---|---|
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 |
21
.github/workflows/go.yml
vendored
Normal file
21
.github/workflows/go.yml
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
name: Go
|
||||||
|
on: [push, pull_request]
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
|
||||||
|
- name: Set up Go 1.13
|
||||||
|
uses: actions/setup-go@v1
|
||||||
|
with:
|
||||||
|
go-version: 1.13
|
||||||
|
id: go
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v1
|
||||||
|
|
||||||
|
- name: Get dependencies
|
||||||
|
run: |
|
||||||
|
go test ./...
|
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
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
language: go
|
language: go
|
||||||
sudo: false
|
sudo: false
|
||||||
go:
|
go:
|
||||||
- "1.11"
|
- '1.13'
|
||||||
install:
|
install:
|
||||||
- "go mod download"
|
- "go mod download"
|
||||||
env:
|
env:
|
||||||
|
15
Dockerfile
15
Dockerfile
@ -1,23 +1,18 @@
|
|||||||
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 && \
|
RUN apk add --no-cache make git && \
|
||||||
|
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 && \
|
tar zxvf /tmp/GeoLite2-Country.tar.gz -C /tmp && \
|
||||||
mv /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /Country.mmdb
|
mv /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /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"]
|
||||||
|
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)/*
|
||||||
|
254
README.md
254
README.md
@ -1,11 +1,9 @@
|
|||||||
<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 tunnel 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://travis-ci.org/Dreamacro/clash">
|
||||||
@ -13,7 +11,7 @@
|
|||||||
alt="Travis-CI">
|
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,34 +20,39 @@
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- HTTP/HTTPS and SOCKS protocol
|
- Local HTTP/HTTPS/SOCKS server
|
||||||
- Surge like configuration
|
- Surge-like configuration format
|
||||||
- GeoIP rule support
|
- GeoIP rule support
|
||||||
- Support Vmess/Shadowsocks/Socks5
|
- Supports Vmess, Shadowsocks, Snell and SOCKS5 protocol
|
||||||
- Support for Netfilter TCP redirect
|
- Supports Netfilter TCP redirecting
|
||||||
|
- Comprehensive HTTP API
|
||||||
|
|
||||||
## 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)
|
||||||
|
|
||||||
Requires Go >= 1.11.
|
Check Clash version with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ clash -v
|
||||||
|
```
|
||||||
|
|
||||||
## Daemon
|
## Daemon
|
||||||
|
|
||||||
Unfortunately, there is no native elegant way to implement golang's daemon.
|
Unfortunately, there is no native and elegant way to implement daemons on Golang.
|
||||||
|
|
||||||
So we can use third-party daemon tools like pm2, supervisor, and so on.
|
So we can use third-party daemon tools like PM2, Supervisor or the like.
|
||||||
|
|
||||||
In the case of [pm2](https://github.com/Unitech/pm2), we can start the daemon this way:
|
In the case of [pm2](https://github.com/Unitech/pm2), we can start the daemon this way:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pm2 start clash
|
$ pm2 start clash
|
||||||
```
|
```
|
||||||
|
|
||||||
If you have Docker installed, you can run clash directly using `docker-compose`.
|
If you have Docker installed, you can run clash directly using `docker-compose`.
|
||||||
@ -58,21 +61,20 @@ If you have Docker installed, you can run clash directly using `docker-compose`.
|
|||||||
|
|
||||||
## 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</summary>
|
||||||
|
|
||||||
```yml
|
```yml
|
||||||
# port of HTTP
|
# port of HTTP
|
||||||
@ -86,6 +88,12 @@ socks-port: 7891
|
|||||||
|
|
||||||
allow-lan: false
|
allow-lan: false
|
||||||
|
|
||||||
|
# Only applicable when setting allow-lan to true
|
||||||
|
# "*": bind all IP addresses
|
||||||
|
# 192.168.122.11: bind a single IPv4 address
|
||||||
|
# "[aaaa::a8aa:ff:fe09:57d8]": bind a single IPv6 address
|
||||||
|
# bind-address: "*"
|
||||||
|
|
||||||
# Rule / Global/ Direct (default is Rule)
|
# Rule / Global/ Direct (default is Rule)
|
||||||
mode: Rule
|
mode: Rule
|
||||||
|
|
||||||
@ -93,84 +101,202 @@ mode: Rule
|
|||||||
# info / warning / error / debug / silent
|
# 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: ""
|
||||||
|
|
||||||
dns:
|
# experimental feature
|
||||||
|
experimental:
|
||||||
|
ignore-resolve-fail: true # ignore dns resolve fail, default value is true
|
||||||
|
|
||||||
|
# authentication of local SOCKS5/HTTP(S) server
|
||||||
|
# authentication:
|
||||||
|
# - "user1:pass1"
|
||||||
|
# - "user2:pass2"
|
||||||
|
|
||||||
|
# # experimental hosts, support wildcard (e.g. *.clash.dev Even *.foo.*.example.com)
|
||||||
|
# # static domain has a higher priority than wildcard domain (foo.example.com > *.example.com)
|
||||||
|
# hosts:
|
||||||
|
# '*.clash.dev': 127.0.0.1
|
||||||
|
# 'alpha.clash.dev': '::1'
|
||||||
|
|
||||||
|
# dns:
|
||||||
# enable: true # set true to enable dns (default is false)
|
# enable: true # set true to enable dns (default is false)
|
||||||
# ipv6: false # default is false
|
# ipv6: false # default is false
|
||||||
# listen: 0.0.0.0:53
|
# listen: 0.0.0.0:53
|
||||||
# enhanced-mode: redir-host
|
# 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
|
||||||
# nameserver:
|
# nameserver:
|
||||||
# - 114.114.114.114
|
# - 114.114.114.114
|
||||||
# - tls://dns.rubyfish.cn:853 # dns over tls
|
# - 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
|
# fallback: # concurrent request with nameserver, fallback used when GEOIP country isn't CN
|
||||||
# - 8.8.8.8
|
# - 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:
|
Proxy:
|
||||||
|
|
||||||
# shadowsocks
|
# shadowsocks
|
||||||
# The types of cipher are consistent with go-shadowsocks2
|
# The supported ciphers(encrypt methods):
|
||||||
# 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
|
# aes-128-gcm aes-192-gcm aes-256-gcm
|
||||||
# In addition to what go-shadowsocks2 supports, it also supports chacha20 rc4-md5 xchacha20-ietf-poly1305
|
# aes-128-cfb aes-192-cfb aes-256-cfb
|
||||||
- { name: "ss1", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password" }
|
# aes-128-ctr aes-192-ctr aes-256-ctr
|
||||||
- { name: "ss2", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password", obfs: tls, obfs-host: bing.com }
|
# rc4-md5 chacha20 chacha20-ietf xchacha20
|
||||||
|
# chacha20-ietf-poly1305 xchacha20-ietf-poly1305
|
||||||
|
- name: "ss1"
|
||||||
|
type: ss
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
cipher: chacha20-ietf-poly1305
|
||||||
|
password: "password"
|
||||||
|
# udp: true
|
||||||
|
|
||||||
|
# old obfs configuration format remove after prerelease
|
||||||
|
- name: "ss2"
|
||||||
|
type: ss
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
cipher: chacha20-ietf-poly1305
|
||||||
|
password: "password"
|
||||||
|
plugin: obfs
|
||||||
|
plugin-opts:
|
||||||
|
mode: tls # or http
|
||||||
|
# host: bing.com
|
||||||
|
|
||||||
|
- name: "ss3"
|
||||||
|
type: ss
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
cipher: chacha20-ietf-poly1305
|
||||||
|
password: "password"
|
||||||
|
plugin: v2ray-plugin
|
||||||
|
plugin-opts:
|
||||||
|
mode: websocket # no QUIC now
|
||||||
|
# tls: true # wss
|
||||||
|
# skip-cert-verify: true
|
||||||
|
# host: bing.com
|
||||||
|
# path: "/"
|
||||||
|
# mux: true
|
||||||
|
# headers:
|
||||||
|
# custom: value
|
||||||
|
|
||||||
# vmess
|
# vmess
|
||||||
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto }
|
- name: "vmess"
|
||||||
# with tls
|
type: vmess
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true }
|
server: server
|
||||||
# with tls and skip-cert-verify
|
port: 443
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true, skip-cert-verify: true }
|
uuid: uuid
|
||||||
# with ws
|
alterId: 32
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path }
|
cipher: auto
|
||||||
# with ws + tls
|
# udp: true
|
||||||
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path, tls: true }
|
# tls: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
# network: ws
|
||||||
|
# ws-path: /path
|
||||||
|
# ws-headers:
|
||||||
|
# Host: v2ray.com
|
||||||
|
|
||||||
# socks5
|
# socks5
|
||||||
- { name: "socks", type: socks5, server: server, port: 443 }
|
- name: "socks"
|
||||||
# socks5 with authentication
|
type: socks5
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, username: "username", password: "password" }
|
server: server
|
||||||
# with tls
|
port: 443
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, tls: true }
|
# username: username
|
||||||
# with tls and skip-cert-verify
|
# password: password
|
||||||
- { name: "socks", type: socks5, server: server, port: 443, tls: true, skip-cert-verify: true }
|
# tls: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
# udp: true
|
||||||
|
|
||||||
# http
|
# http
|
||||||
- { name: "http", type: http, server: server, port: 443 }
|
- name: "http"
|
||||||
# http with authentication
|
type: http
|
||||||
- { name: "http", type: http, server: server, port: 443, username: "username", password: "password" }
|
server: server
|
||||||
# with tls (https)
|
port: 443
|
||||||
- { name: "http", type: http, server: server, port: 443, tls: true }
|
# username: username
|
||||||
# with tls (https) and skip-cert-verify
|
# password: password
|
||||||
- { name: "http", type: http, server: server, port: 443, tls: true, skip-cert-verify: true }
|
# tls: true # https
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
# snell
|
||||||
|
- name: "snell"
|
||||||
|
type: snell
|
||||||
|
server: server
|
||||||
|
port: 44046
|
||||||
|
psk: yourpsk
|
||||||
|
# obfs-opts:
|
||||||
|
# mode: http # or tls
|
||||||
|
# host: bing.com
|
||||||
|
|
||||||
Proxy Group:
|
Proxy Group:
|
||||||
# url-test select which proxy will be used by benchmarking speed to a URL.
|
# 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 }
|
- 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.
|
# 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 }
|
- 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
|
# select is used for selecting proxy or proxy group
|
||||||
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
||||||
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
|
- name: Proxy
|
||||||
|
type: select
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- vmess1
|
||||||
|
- auto
|
||||||
|
|
||||||
Rule:
|
Rule:
|
||||||
- DOMAIN-SUFFIX,google.com,Proxy
|
- DOMAIN-SUFFIX,google.com,auto
|
||||||
- DOMAIN-KEYWORD,google,Proxy
|
- DOMAIN-KEYWORD,google,auto
|
||||||
- DOMAIN,google.com,Proxy
|
- DOMAIN,google.com,auto
|
||||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
- DOMAIN-SUFFIX,ad.com,REJECT
|
||||||
- IP-CIDR,127.0.0.0/8,DIRECT
|
- IP-CIDR,127.0.0.0/8,DIRECT
|
||||||
|
# rename SOURCE-IP-CIDR and would remove after prerelease
|
||||||
|
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
||||||
- GEOIP,CN,DIRECT
|
- GEOIP,CN,DIRECT
|
||||||
|
- DST-PORT,80,DIRECT
|
||||||
|
- SRC-PORT,7777,DIRECT
|
||||||
# FINAL would remove after prerelease
|
# FINAL would remove after prerelease
|
||||||
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
||||||
- MATCH,Proxy
|
- MATCH,auto
|
||||||
```
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## Documentations
|
||||||
|
https://clash.gitbook.io/
|
||||||
|
|
||||||
## Thanks
|
## Thanks
|
||||||
|
|
||||||
@ -186,5 +312,5 @@ 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
|
- [ ] Connection manager
|
||||||
|
@ -10,32 +10,27 @@ 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)
|
||||||
|
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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,8 +7,13 @@ import (
|
|||||||
|
|
||||||
// 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)
|
||||||
|
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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,38 +3,33 @@ package adapters
|
|||||||
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, source C.SourceType) *SocketAdapter {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, netType C.NetWork) *SocketAdapter {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.Source = source
|
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: metadata,
|
metadata: metadata,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,28 +5,27 @@ import (
|
|||||||
"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 {
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
|
||||||
AddrType: int(target[0]),
|
AddrType: int(target[0]),
|
||||||
}
|
}
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
metadata.Host = string(target[2 : 2+target[1]])
|
metadata.Host = string(target[2 : 2+target[1]])
|
||||||
metadata.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]))
|
||||||
case socks.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
ip := net.IP(target[1 : 1+net.IPv4len])
|
ip := net.IP(target[1 : 1+net.IPv4len])
|
||||||
metadata.IP = &ip
|
metadata.DstIP = &ip
|
||||||
metadata.Port = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
case socks.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
ip := net.IP(target[1 : 1+net.IPv6len])
|
ip := net.IP(target[1 : 1+net.IPv6len])
|
||||||
metadata.IP = &ip
|
metadata.DstIP = &ip
|
||||||
metadata.Port = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
@ -41,11 +40,11 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
Source: C.HTTP,
|
Type: C.HTTP,
|
||||||
AddrType: C.AtypDomainName,
|
AddrType: C.AtypDomainName,
|
||||||
Host: host,
|
Host: host,
|
||||||
IP: nil,
|
DstIP: nil,
|
||||||
Port: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
@ -56,8 +55,18 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
default:
|
default:
|
||||||
metadata.AddrType = C.AtypIPv4
|
metadata.AddrType = C.AtypIPv4
|
||||||
}
|
}
|
||||||
metadata.IP = &ip
|
metadata.DstIP = &ip
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
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
|
||||||
|
}
|
||||||
|
207
adapters/outbound/base.go
Normal file
207
adapters/outbound/base.go
Normal file
@ -0,0 +1,207 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
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
|
||||||
|
tp C.AdapterType
|
||||||
|
udp bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Name() string {
|
||||||
|
return b.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Type() C.AdapterType {
|
||||||
|
return b.tp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
return nil, nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) SupportUDP() bool {
|
||||||
|
return b.udp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Destroy() {}
|
||||||
|
|
||||||
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": b.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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 struct {
|
||||||
|
net.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(c net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
|
return &packetConn{c, []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()
|
||||||
|
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}
|
||||||
|
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}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyGroupOption contain the common options for all kind of ProxyGroup
|
||||||
|
type ProxyGroupOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Proxies []string `proxy:"proxies"`
|
||||||
|
}
|
@ -1,57 +1,49 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
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
|
|
||||||
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) {
|
|
||||||
address := net.JoinHostPort(metadata.Host, metadata.Port)
|
|
||||||
if metadata.IP != nil {
|
|
||||||
address = net.JoinHostPort(metadata.IP.String(), metadata.Port)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := net.DialTimeout("tcp", address, tcpTimeout)
|
c, err := dialContext(ctx, "tcp", address)
|
||||||
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) MarshalJSON() ([]byte, error) {
|
func (d *Direct) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
return json.Marshal(map[string]string{
|
pc, err := net.ListenPacket("udp", "")
|
||||||
"type": d.Type().String(),
|
if err != nil {
|
||||||
})
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", metadata.RemoteAddress())
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(pc, d), addr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
return &Direct{}
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: "DIRECT",
|
||||||
|
tp: C.Direct,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,19 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type proxy struct {
|
|
||||||
RawProxy C.Proxy
|
|
||||||
Valid bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
name string
|
*Base
|
||||||
proxies []*proxy
|
proxies []C.Proxy
|
||||||
rawURL string
|
rawURL string
|
||||||
interval time.Duration
|
interval time.Duration
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
@ -29,45 +26,38 @@ type FallbackOption struct {
|
|||||||
Interval int `proxy:"interval"`
|
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 {
|
func (f *Fallback) Now() string {
|
||||||
_, proxy := f.findNextValidProxy(0)
|
proxy := f.findAliveProxy()
|
||||||
if proxy != nil {
|
return proxy.Name()
|
||||||
return proxy.RawProxy.Name()
|
|
||||||
}
|
|
||||||
return f.proxies[0].RawProxy.Name()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
idx := 0
|
proxy := f.findAliveProxy()
|
||||||
var proxy *proxy
|
c, err := proxy.DialContext(ctx, metadata)
|
||||||
for {
|
if err == nil {
|
||||||
idx, proxy = f.findNextValidProxy(idx)
|
c.AppendToChains(f)
|
||||||
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)
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
pc, addr, err := proxy.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return pc, addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) SupportUDP() bool {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
return proxy.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
var all []string
|
||||||
for _, proxy := range f.proxies {
|
for _, proxy := range f.proxies {
|
||||||
all = append(all, proxy.RawProxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]interface{}{
|
||||||
"type": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
@ -76,7 +66,7 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Close() {
|
func (f *Fallback) Destroy() {
|
||||||
f.done <- struct{}{}
|
f.done <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -94,13 +84,13 @@ Loop:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) findNextValidProxy(start int) (int, *proxy) {
|
func (f *Fallback) findAliveProxy() C.Proxy {
|
||||||
for i := start; i < len(f.proxies); i++ {
|
for _, proxy := range f.proxies {
|
||||||
if f.proxies[i].Valid {
|
if proxy.Alive() {
|
||||||
return i, f.proxies[i]
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1, nil
|
return f.proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) validTest() {
|
func (f *Fallback) validTest() {
|
||||||
@ -108,9 +98,8 @@ func (f *Fallback) validTest() {
|
|||||||
wg.Add(len(f.proxies))
|
wg.Add(len(f.proxies))
|
||||||
|
|
||||||
for _, p := range f.proxies {
|
for _, p := range f.proxies {
|
||||||
go func(p *proxy) {
|
go func(p C.Proxy) {
|
||||||
_, err := DelayTest(p.RawProxy, f.rawURL)
|
p.URLTest(context.Background(), f.rawURL)
|
||||||
p.Valid = err == nil
|
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}(p)
|
}(p)
|
||||||
}
|
}
|
||||||
@ -129,17 +118,13 @@ func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
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{
|
Fallback := &Fallback{
|
||||||
name: option.Name,
|
Base: &Base{
|
||||||
proxies: warpperProxies,
|
name: option.Name,
|
||||||
|
tp: C.Fallback,
|
||||||
|
},
|
||||||
|
proxies: proxies,
|
||||||
rawURL: option.URL,
|
rawURL: option.URL,
|
||||||
interval: interval,
|
interval: interval,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
|
@ -3,9 +3,9 @@ package adapters
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@ -16,23 +16,9 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// HTTPAdapter is a proxy adapter
|
|
||||||
type HTTPAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (ha *HTTPAdapter) Close() {
|
|
||||||
ha.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ha *HTTPAdapter) Conn() net.Conn {
|
|
||||||
return ha.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type Http struct {
|
type Http struct {
|
||||||
|
*Base
|
||||||
addr string
|
addr string
|
||||||
name string
|
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
@ -50,16 +36,8 @@ type HttpOption struct {
|
|||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) Name() string {
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return h.name
|
c, err := dialContext(ctx, "tcp", h.addr)
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) Type() C.AdapterType {
|
|
||||||
return C.Http
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
c, err := net.DialTimeout("tcp", h.addr, tcpTimeout)
|
|
||||||
if err == nil && h.tls {
|
if err == nil && h.tls {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
err = cc.Handshake()
|
err = cc.Handshake()
|
||||||
@ -74,16 +52,16 @@ func (h *Http) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err erro
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &HTTPAdapter{conn: c}, nil
|
return newConn(c, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
buf.WriteString("CONNECT ")
|
addr := metadata.RemoteAddress()
|
||||||
buf.WriteString(net.JoinHostPort(metadata.Host, metadata.Port))
|
buf.WriteString("CONNECT " + addr + " HTTP/1.1\r\n")
|
||||||
buf.WriteString(" HTTP/1.1\r\n")
|
buf.WriteString("Host: " + metadata.String() + "\r\n")
|
||||||
buf.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
buf.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
@ -104,24 +82,22 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode == 200 {
|
if resp.StatusCode == http.StatusOK {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode == 407 {
|
if resp.StatusCode == http.StatusProxyAuthRequired {
|
||||||
return errors.New("HTTP need auth")
|
return errors.New("HTTP need auth")
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode == 405 {
|
if resp.StatusCode == http.StatusMethodNotAllowed {
|
||||||
return errors.New("CONNECT method not allowed by proxy")
|
return errors.New("CONNECT method not allowed by proxy")
|
||||||
}
|
}
|
||||||
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) MarshalJSON() ([]byte, error) {
|
if resp.StatusCode >= http.StatusInternalServerError {
|
||||||
return json.Marshal(map[string]string{
|
return errors.New(resp.Status)
|
||||||
"type": h.Type().String(),
|
}
|
||||||
})
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHttp(option HttpOption) *Http {
|
func NewHttp(option HttpOption) *Http {
|
||||||
@ -130,15 +106,16 @@ func NewHttp(option HttpOption) *Http {
|
|||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ClientSessionCache: getClientSessionCache(),
|
ClientSessionCache: getClientSessionCache(),
|
||||||
MinVersion: tls.VersionTLS11,
|
|
||||||
MaxVersion: tls.VersionTLS12,
|
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Http{
|
return &Http{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Http,
|
||||||
|
},
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
name: option.Name,
|
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
|
172
adapters/outbound/loadbalance.go
Normal file
172
adapters/outbound/loadbalance.go
Normal file
@ -0,0 +1,172 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LoadBalance struct {
|
||||||
|
*Base
|
||||||
|
proxies []C.Proxy
|
||||||
|
maxRetry int
|
||||||
|
rawURL string
|
||||||
|
interval time.Duration
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
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))))
|
||||||
|
buckets := int32(len(lb.proxies))
|
||||||
|
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||||
|
idx := jumpHash(key, buckets)
|
||||||
|
proxy := lb.proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
c, err = proxy.DialContext(ctx, metadata)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err = lb.proxies[0].DialContext(ctx, metadata)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (pc C.PacketConn, addr net.Addr, err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(lb)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
|
buckets := int32(len(lb.proxies))
|
||||||
|
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||||
|
idx := jumpHash(key, buckets)
|
||||||
|
proxy := lb.proxies[idx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy.DialUDP(metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lb.proxies[0].DialUDP(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) SupportUDP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) Destroy() {
|
||||||
|
lb.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) validTest() {
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(len(lb.proxies))
|
||||||
|
|
||||||
|
for _, p := range lb.proxies {
|
||||||
|
go func(p C.Proxy) {
|
||||||
|
p.URLTest(context.Background(), lb.rawURL)
|
||||||
|
wg.Done()
|
||||||
|
}(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) loop() {
|
||||||
|
tick := time.NewTicker(lb.interval)
|
||||||
|
go lb.validTest()
|
||||||
|
Loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-tick.C:
|
||||||
|
go lb.validTest()
|
||||||
|
case <-lb.done:
|
||||||
|
break Loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoadBalanceOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Proxies []string `proxy:"proxies"`
|
||||||
|
URL string `proxy:"url"`
|
||||||
|
Interval int `proxy:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoadBalance(option LoadBalanceOption, proxies []C.Proxy) (*LoadBalance, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("Provide at least one proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := time.Duration(option.Interval) * time.Second
|
||||||
|
|
||||||
|
lb := &LoadBalance{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.LoadBalance,
|
||||||
|
},
|
||||||
|
proxies: proxies,
|
||||||
|
maxRetry: 3,
|
||||||
|
rawURL: option.URL,
|
||||||
|
interval: interval,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
go lb.loop()
|
||||||
|
return lb, nil
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
@ -9,42 +9,21 @@ 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 {
|
|
||||||
return C.Reject
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Reject) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
return &RejectAdapter{conn: &NopConn{}}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Reject) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]string{
|
|
||||||
"type": r.Type().String(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
return &Reject{}
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "REJECT",
|
||||||
|
tp: C.Reject,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type NopConn struct{}
|
type NopConn struct{}
|
||||||
|
@ -1,17 +1,19 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"sort"
|
"net"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
name string
|
*Base
|
||||||
selected C.Proxy
|
selected C.Proxy
|
||||||
proxies map[string]C.Proxy
|
proxies map[string]C.Proxy
|
||||||
|
proxyList []string
|
||||||
}
|
}
|
||||||
|
|
||||||
type SelectorOption struct {
|
type SelectorOption struct {
|
||||||
@ -19,28 +21,31 @@ type SelectorOption struct {
|
|||||||
Proxies []string `proxy:"proxies"`
|
Proxies []string `proxy:"proxies"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Name() string {
|
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return s.name
|
c, err := s.selected.DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Type() C.AdapterType {
|
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
return C.Selector
|
pc, addr, err := s.selected.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return pc, addr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
func (s *Selector) SupportUDP() bool {
|
||||||
return s.selected.Generator(metadata)
|
return s.selected.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
|
||||||
for k := range s.proxies {
|
|
||||||
all = append(all, k)
|
|
||||||
}
|
|
||||||
sort.Strings(all)
|
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]interface{}{
|
||||||
"type": s.Type().String(),
|
"type": s.Type().String(),
|
||||||
"now": s.Now(),
|
"now": s.Now(),
|
||||||
"all": all,
|
"all": s.proxyList,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,14 +68,20 @@ func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mapping := make(map[string]C.Proxy)
|
mapping := make(map[string]C.Proxy)
|
||||||
for _, proxy := range proxies {
|
proxyList := make([]string, len(proxies))
|
||||||
|
for idx, proxy := range proxies {
|
||||||
mapping[proxy.Name()] = proxy
|
mapping[proxy.Name()] = proxy
|
||||||
|
proxyList[idx] = proxy.Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
s := &Selector{
|
s := &Selector{
|
||||||
name: name,
|
Base: &Base{
|
||||||
proxies: mapping,
|
name: name,
|
||||||
selected: proxies[0],
|
tp: C.Selector,
|
||||||
|
},
|
||||||
|
proxies: mapping,
|
||||||
|
selected: proxies[0],
|
||||||
|
proxyList: proxyList,
|
||||||
}
|
}
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
@ -1,75 +1,105 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/simple-obfs"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
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
|
server string
|
||||||
obfs string
|
cipher core.Cipher
|
||||||
obfsHost string
|
|
||||||
cipher core.Cipher
|
// obfs
|
||||||
|
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) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
|
c, err := dialContext(ctx, "tcp", ss.server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error", ss.server)
|
return nil, fmt.Errorf("%s connect error: %s", ss.server, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
switch ss.obfs {
|
switch ss.obfsMode {
|
||||||
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.server)
|
||||||
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: %s", ss.server, err.Error())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
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 newConn(c, ss), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
pc, err := net.ListenPacket("udp", "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ss.server)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
targetAddr := socks5.ParseAddr(metadata.RemoteAddress())
|
||||||
|
if targetAddr == nil {
|
||||||
|
return nil, nil, fmt.Errorf("parse address error: %v:%v", metadata.String(), metadata.DstPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
pc = ss.cipher.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssUDPConn{PacketConn: pc, rAddr: targetAddr}, ss), addr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
||||||
@ -87,37 +117,92 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
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: %s", server, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "tls" && opts.Mode != "http" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", server, 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: %s", server, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "websocket" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", server, 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,
|
tp: C.Shadowsocks,
|
||||||
obfs: obfs,
|
udp: option.UDP,
|
||||||
obfsHost: obfsHost,
|
},
|
||||||
|
server: server,
|
||||||
|
cipher: ciph,
|
||||||
|
|
||||||
|
obfsMode: obfsMode,
|
||||||
|
v2rayOption: v2rayOption,
|
||||||
|
obfsOption: obfsOption,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
type ssUDPConn struct {
|
||||||
var buf [][]byte
|
net.PacketConn
|
||||||
aType := uint8(metadata.AddrType)
|
rAddr socks5.Addr
|
||||||
p, _ := strconv.Atoi(metadata.Port)
|
}
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
|
||||||
switch metadata.AddrType {
|
func (uc *ssUDPConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
case socks.AtypDomainName:
|
packet, err := socks5.EncodeUDPPacket(uc.rAddr, b)
|
||||||
len := uint8(len(metadata.Host))
|
if err != nil {
|
||||||
host := []byte(metadata.Host)
|
return
|
||||||
buf = [][]byte{{aType, len}, host, port}
|
}
|
||||||
case socks.AtypIPv4:
|
return uc.PacketConn.WriteTo(packet[3:], addr)
|
||||||
host := metadata.IP.To4()
|
}
|
||||||
buf = [][]byte{{aType}, host, port}
|
|
||||||
case socks.AtypIPv6:
|
func (uc *ssUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
host := metadata.IP.To16()
|
n, a, e := uc.PacketConn.ReadFrom(b)
|
||||||
buf = [][]byte{{aType}, host, port}
|
addr := socks5.SplitAddr(b[:n])
|
||||||
}
|
copy(b, b[len(addr):])
|
||||||
return bytes.Join(buf, nil)
|
return n - len(addr), a, e
|
||||||
}
|
}
|
||||||
|
72
adapters/outbound/snell.go
Normal file
72
adapters/outbound/snell.go
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
||||||
|
"github.com/Dreamacro/clash/component/snell"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Snell struct {
|
||||||
|
*Base
|
||||||
|
server string
|
||||||
|
psk []byte
|
||||||
|
obfsOption *simpleObfsOption
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnellOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Psk string `proxy:"psk"`
|
||||||
|
ObfsOpts map[string]interface{} `proxy:"obfs-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := dialContext(ctx, "tcp", s.server)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", s.server, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
switch s.obfsOption.Mode {
|
||||||
|
case "tls":
|
||||||
|
c = obfs.NewTLSObfs(c, s.obfsOption.Host)
|
||||||
|
case "http":
|
||||||
|
_, port, _ := net.SplitHostPort(s.server)
|
||||||
|
c = obfs.NewHTTPObfs(c, s.obfsOption.Host, port)
|
||||||
|
}
|
||||||
|
c = snell.StreamConn(c, s.psk)
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
err = snell.WriteHeader(c, metadata.String(), uint(port))
|
||||||
|
return newConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
|
server := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
psk := []byte(option.Psk)
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
|
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
||||||
|
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
||||||
|
return nil, fmt.Errorf("snell %s initialize obfs error: %s", server, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if obfsOption.Mode != "tls" && obfsOption.Mode != "http" {
|
||||||
|
return nil, fmt.Errorf("snell %s obfs mode error: %s", server, obfsOption.Mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Snell{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Snell,
|
||||||
|
},
|
||||||
|
server: server,
|
||||||
|
psk: psk,
|
||||||
|
obfsOption: obfsOption,
|
||||||
|
}, nil
|
||||||
|
}
|
@ -1,37 +1,21 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
"net"
|
"net"
|
||||||
"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"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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 {
|
||||||
|
*Base
|
||||||
addr string
|
addr string
|
||||||
name string
|
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
@ -46,19 +30,12 @@ type Socks5Option struct {
|
|||||||
UserName string `proxy:"username,omitempty"`
|
UserName string `proxy:"username,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
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) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return ss.name
|
c, err := dialContext(ctx, "tcp", ss.addr)
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) Type() C.AdapterType {
|
|
||||||
return C.Socks5
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
if err == nil && ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
@ -70,75 +47,79 @@ func (ss *Socks5) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err e
|
|||||||
return nil, fmt.Errorf("%s connect error", ss.addr)
|
return nil, fmt.Errorf("%s connect error", ss.addr)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
if err := ss.shakeHand(metadata, c); err != nil {
|
var user *socks5.User
|
||||||
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &Socks5Adapter{conn: c}, nil
|
return newConn(c, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss *Socks5) MarshalJSON() ([]byte, error) {
|
func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, _ net.Addr, err error) {
|
||||||
return json.Marshal(map[string]string{
|
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
||||||
"type": ss.Type().String(),
|
defer cancel()
|
||||||
})
|
c, err := dialContext(ctx, "tcp", ss.addr)
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|
||||||
buf := make([]byte, socks.MaxAddrLen)
|
|
||||||
var err error
|
|
||||||
|
|
||||||
// VER, NMETHODS, METHODS
|
|
||||||
if len(ss.user) > 0 {
|
|
||||||
_, err = rw.Write([]byte{5, 1, 2})
|
|
||||||
} else {
|
|
||||||
_, err = rw.Write([]byte{5, 1, 0})
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
err = fmt.Errorf("%s connect error", ss.addr)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// VER, METHOD
|
if ss.tls {
|
||||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
return err
|
err = cc.Handshake()
|
||||||
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
if buf[0] != 5 {
|
defer func() {
|
||||||
return errors.New("SOCKS version error")
|
if err != nil {
|
||||||
}
|
c.Close()
|
||||||
|
|
||||||
if buf[1] == 2 {
|
|
||||||
// password protocol version
|
|
||||||
authMsg := &bytes.Buffer{}
|
|
||||||
authMsg.WriteByte(1)
|
|
||||||
authMsg.WriteByte(uint8(len(ss.user)))
|
|
||||||
authMsg.WriteString(ss.user)
|
|
||||||
authMsg.WriteByte(uint8(len(ss.pass)))
|
|
||||||
authMsg.WriteString(ss.pass)
|
|
||||||
|
|
||||||
if _, err := rw.Write(authMsg.Bytes()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
tcpKeepAlive(c)
|
||||||
return err
|
var user *socks5.User
|
||||||
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
}
|
}
|
||||||
|
|
||||||
if buf[1] != 0 {
|
|
||||||
return errors.New("rejected username/password")
|
|
||||||
}
|
|
||||||
} else if buf[1] != 0 {
|
|
||||||
return errors.New("SOCKS need auth")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// VER, CMD, RSV, ADDR
|
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
|
if err != nil {
|
||||||
return err
|
err = fmt.Errorf("%v client hanshake error", err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
|
addr, err := net.ResolveUDPAddr("udp", bindAddr.String())
|
||||||
return err
|
if err != nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
targetAddr := socks5.ParseAddr(metadata.RemoteAddress())
|
||||||
|
if targetAddr == nil {
|
||||||
|
return nil, nil, fmt.Errorf("parse address error: %v:%v", metadata.String(), metadata.DstPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := net.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(&socksUDPConn{PacketConn: pc, rAddr: targetAddr, tcpConn: c}, ss), addr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
@ -147,15 +128,17 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
|||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ClientSessionCache: getClientSessionCache(),
|
ClientSessionCache: getClientSessionCache(),
|
||||||
MinVersion: tls.VersionTLS11,
|
|
||||||
MaxVersion: tls.VersionTLS12,
|
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &Socks5{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Socks5,
|
||||||
|
udp: option.UDP,
|
||||||
|
},
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
name: option.Name,
|
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
@ -163,3 +146,37 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
|||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type socksUDPConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
rAddr socks5.Addr
|
||||||
|
tcpConn net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksUDPConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(uc.rAddr, b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return uc.PacketConn.WriteTo(packet, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, a, 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
|
||||||
|
}
|
||||||
|
// due to DecodeUDPPacket is mutable, record addr length
|
||||||
|
addrLength := len(addr)
|
||||||
|
copy(b, payload)
|
||||||
|
return n - addrLength - 3, a, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *socksUDPConn) Close() error {
|
||||||
|
uc.tcpConn.Close()
|
||||||
|
return uc.PacketConn.Close()
|
||||||
|
}
|
||||||
|
@ -1,18 +1,19 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"sort"
|
"net"
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/picker"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
name string
|
*Base
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
rawURL string
|
rawURL string
|
||||||
fast C.Proxy
|
fast C.Proxy
|
||||||
@ -28,24 +29,32 @@ type URLTestOption struct {
|
|||||||
Interval int `proxy:"interval"`
|
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 {
|
func (u *URLTest) Now() string {
|
||||||
return u.fast.Name()
|
return u.fast.Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
a, err := u.fast.Generator(metadata)
|
for i := 0; i < 3; i++ {
|
||||||
if err != nil {
|
c, err = u.fast.DialContext(ctx, metadata)
|
||||||
go u.speedTest()
|
if err == nil {
|
||||||
|
c.AppendToChains(u)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u.fallback()
|
||||||
}
|
}
|
||||||
return a, err
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
pc, addr, err := u.fast.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return pc, addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) SupportUDP() bool {
|
||||||
|
return u.fast.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
@ -53,7 +62,6 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
for _, proxy := range u.proxies {
|
for _, proxy := range u.proxies {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
sort.Strings(all)
|
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]interface{}{
|
||||||
"type": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
@ -61,7 +69,7 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Close() {
|
func (u *URLTest) Destroy() {
|
||||||
u.done <- struct{}{}
|
u.done <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,42 +87,49 @@ Loop:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) fallback() {
|
||||||
|
fast := u.proxies[0]
|
||||||
|
min := fast.LastDelay()
|
||||||
|
for _, proxy := range u.proxies[1:] {
|
||||||
|
if !proxy.Alive() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delay := proxy.LastDelay()
|
||||||
|
if delay < min {
|
||||||
|
fast = proxy
|
||||||
|
min = delay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u.fast = fast
|
||||||
|
}
|
||||||
|
|
||||||
func (u *URLTest) speedTest() {
|
func (u *URLTest) speedTest() {
|
||||||
if atomic.AddInt32(&u.once, 1) != 1 {
|
if !atomic.CompareAndSwapInt32(&u.once, 0, 1) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer atomic.StoreInt32(&u.once, 0)
|
defer atomic.StoreInt32(&u.once, 0)
|
||||||
|
|
||||||
wg := sync.WaitGroup{}
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
wg.Add(len(u.proxies))
|
defer cancel()
|
||||||
c := make(chan interface{})
|
picker := picker.WithoutAutoCancel(ctx)
|
||||||
fast := selectFast(c)
|
|
||||||
timer := time.NewTimer(u.interval)
|
|
||||||
|
|
||||||
for _, p := range u.proxies {
|
for _, p := range u.proxies {
|
||||||
go func(p C.Proxy) {
|
proxy := p
|
||||||
_, err := DelayTest(p, u.rawURL)
|
picker.Go(func() (interface{}, error) {
|
||||||
if err == nil {
|
_, err := proxy.URLTest(ctx, u.rawURL)
|
||||||
c <- p
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
wg.Done()
|
return proxy, nil
|
||||||
}(p)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
fast := picker.WaitWithoutCancel()
|
||||||
wg.Wait()
|
if fast != nil {
|
||||||
close(c)
|
u.fast = fast.(C.Proxy)
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-timer.C:
|
|
||||||
// Wait for fast to return or close.
|
|
||||||
<-fast
|
|
||||||
case p, open := <-fast:
|
|
||||||
if open {
|
|
||||||
u.fast = p.(C.Proxy)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
picker.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
||||||
@ -128,7 +143,10 @@ func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
|||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
interval := time.Duration(option.Interval) * time.Second
|
||||||
urlTest := &URLTest{
|
urlTest := &URLTest{
|
||||||
name: option.Name,
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.URLTest,
|
||||||
|
},
|
||||||
proxies: proxies[:],
|
proxies: proxies[:],
|
||||||
rawURL: option.URL,
|
rawURL: option.URL,
|
||||||
fast: proxies[0],
|
fast: proxies[0],
|
||||||
|
@ -1,15 +1,19 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/dns"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -21,39 +25,6 @@ var (
|
|||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
// DelayTest get the delay for the specified URL
|
|
||||||
func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
|
|
||||||
addr, err := urlToMetadata(url)
|
|
||||||
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)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -75,27 +46,12 @@ 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)
|
||||||
@ -109,3 +65,116 @@ func getClientSessionCache() tls.ClientSessionCache {
|
|||||||
})
|
})
|
||||||
return globalClientSessionCache
|
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 dialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer := net.Dialer{}
|
||||||
|
|
||||||
|
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, host string, ipv6 bool) {
|
||||||
|
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 = dns.ResolveIPv6(host)
|
||||||
|
} else {
|
||||||
|
ip, result.error = dns.ResolveIPv4(host)
|
||||||
|
}
|
||||||
|
if result.error != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.resolved = true
|
||||||
|
|
||||||
|
if ipv6 {
|
||||||
|
result.Conn, result.error = dialer.DialContext(ctx, "tcp6", net.JoinHostPort(ip.String(), port))
|
||||||
|
} else {
|
||||||
|
result.Conn, result.error = dialer.DialContext(ctx, "tcp4", net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
go startRacer(ctx, host, false)
|
||||||
|
go startRacer(ctx, 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, err := dns.ResolveIP(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package adapters
|
package adapters
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -11,83 +11,77 @@ import (
|
|||||||
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
|
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 (v *Vmess) Name() string {
|
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return v.name
|
c, err := dialContext(ctx, "tcp", v.server)
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) Type() C.AdapterType {
|
|
||||||
return C.Vmess
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
|
||||||
c, err := net.DialTimeout("tcp", v.server, tcpTimeout)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error", v.server)
|
return nil, fmt.Errorf("%s connect error", v.server)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = v.client.New(c, parseVmessAddr(metadata))
|
c, err = v.client.New(c, parseVmessAddr(metadata))
|
||||||
return &VmessAdapter{conn: c}, err
|
return newConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vmess) MarshalJSON() ([]byte, error) {
|
func (v *Vmess) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
return json.Marshal(map[string]interface{}{
|
ctx, cancel := context.WithTimeout(context.Background(), tcpTimeout)
|
||||||
"type": v.Type().String(),
|
defer cancel()
|
||||||
})
|
c, err := dialContext(ctx, "tcp", v.server)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("%s connect error", v.server)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = v.client.New(c, parseVmessAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
return newPacketConn(&vmessUDPConn{Conn: c}, v), c.RemoteAddr(), 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,
|
||||||
HostName: option.Server,
|
HostName: option.Server,
|
||||||
Port: strconv.Itoa(option.Port),
|
Port: strconv.Itoa(option.Port),
|
||||||
NetWork: option.Network,
|
NetWork: option.Network,
|
||||||
WebSocketPath: option.WSPath,
|
WebSocketPath: option.WSPath,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
WebSocketHeaders: option.WSHeaders,
|
||||||
SessionCacahe: getClientSessionCache(),
|
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{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Vmess,
|
||||||
|
udp: true,
|
||||||
|
},
|
||||||
server: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
server: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
client: client,
|
client: client,
|
||||||
}, nil
|
}, nil
|
||||||
@ -100,11 +94,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)
|
||||||
@ -112,10 +106,24 @@ 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 vmessUDPConn struct {
|
||||||
|
net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
return uc.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uc *vmessUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, err := uc.Conn.Read(b)
|
||||||
|
return n, uc.RemoteAddr(), err
|
||||||
|
}
|
||||||
|
15
common/cache/cache.go
vendored
15
common/cache/cache.go
vendored
@ -44,6 +44,21 @@ func (c *cache) Get(key interface{}) interface{} {
|
|||||||
return elm.Payload
|
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() {
|
func (c *cache) cleanup() {
|
||||||
c.mapping.Range(func(k, v interface{}) bool {
|
c.mapping.Range(func(k, v interface{}) bool {
|
||||||
key := k.(string)
|
key := k.(string)
|
||||||
|
30
common/cache/cache_test.go
vendored
30
common/cache/cache_test.go
vendored
@ -4,6 +4,8 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCache_Basic(t *testing.T) {
|
func TestCache_Basic(t *testing.T) {
|
||||||
@ -14,32 +16,30 @@ func TestCache_Basic(t *testing.T) {
|
|||||||
c.Put("string", "a", ttl)
|
c.Put("string", "a", ttl)
|
||||||
|
|
||||||
i := c.Get("int")
|
i := c.Get("int")
|
||||||
if i.(int) != 1 {
|
assert.Equal(t, i.(int), 1, "should recv 1")
|
||||||
t.Error("should recv 1")
|
|
||||||
}
|
|
||||||
|
|
||||||
s := c.Get("string")
|
s := c.Get("string")
|
||||||
if s.(string) != "a" {
|
assert.Equal(t, s.(string), "a", "should recv 'a'")
|
||||||
t.Error("should recv 'a'")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCache_TTL(t *testing.T) {
|
func TestCache_TTL(t *testing.T) {
|
||||||
interval := 200 * time.Millisecond
|
interval := 200 * time.Millisecond
|
||||||
ttl := 20 * time.Millisecond
|
ttl := 20 * time.Millisecond
|
||||||
|
now := time.Now()
|
||||||
c := New(interval)
|
c := New(interval)
|
||||||
c.Put("int", 1, ttl)
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("int2", 2, ttl)
|
||||||
|
|
||||||
i := c.Get("int")
|
i := c.Get("int")
|
||||||
if i.(int) != 1 {
|
_, expired := c.GetWithExpire("int2")
|
||||||
t.Error("should recv 1")
|
assert.Equal(t, i.(int), 1, "should recv 1")
|
||||||
}
|
assert.True(t, now.Before(expired))
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
time.Sleep(ttl * 2)
|
||||||
i = c.Get("int")
|
i = c.Get("int")
|
||||||
if i != nil {
|
j, _ := c.GetWithExpire("int2")
|
||||||
t.Error("should recv nil")
|
assert.Nil(t, i, "should recv nil")
|
||||||
}
|
assert.Nil(t, j, "should recv nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCache_AutoCleanup(t *testing.T) {
|
func TestCache_AutoCleanup(t *testing.T) {
|
||||||
@ -50,9 +50,9 @@ func TestCache_AutoCleanup(t *testing.T) {
|
|||||||
|
|
||||||
time.Sleep(ttl * 2)
|
time.Sleep(ttl * 2)
|
||||||
i := c.Get("int")
|
i := c.Get("int")
|
||||||
if i != nil {
|
j, _ := c.GetWithExpire("int")
|
||||||
t.Error("should recv nil")
|
assert.Nil(t, i, "should recv nil")
|
||||||
}
|
assert.Nil(t, j, "should recv nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCache_AutoGC(t *testing.T) {
|
func TestCache_AutoGC(t *testing.T) {
|
||||||
|
157
common/cache/lrucache.go
vendored
Normal file
157
common/cache/lrucache.go
vendored
Normal file
@ -0,0 +1,157 @@
|
|||||||
|
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)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
key interface{}
|
||||||
|
value interface{}
|
||||||
|
expires int64
|
||||||
|
}
|
117
common/cache/lrucache_test.go
vendored
Normal file
117
common/cache/lrucache_test.go
vendored
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
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)
|
||||||
|
}
|
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
|
||||||
|
}
|
@ -1,22 +1,89 @@
|
|||||||
package picker
|
package picker
|
||||||
|
|
||||||
import "context"
|
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{}
|
||||||
|
|
||||||
|
firstDone chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPicker(ctx context.Context, cancel func()) *Picker {
|
||||||
|
return &Picker{
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
firstDone: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithoutAutoCancel returns a new Picker and an associated Context derived from ctx,
|
||||||
|
// but it wouldn't cancel context when the first element return.
|
||||||
|
func WithoutAutoCancel(ctx context.Context) *Picker {
|
||||||
|
return newPicker(ctx, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// WaitWithoutCancel blocks until the first result return, if timeout will return nil.
|
||||||
|
func (p *Picker) WaitWithoutCancel() interface{} {
|
||||||
|
select {
|
||||||
|
case <-p.firstDone:
|
||||||
|
return p.result
|
||||||
|
case <-p.ctx.Done():
|
||||||
|
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)
|
||||||
|
|
||||||
func SelectFast(ctx context.Context, in <-chan interface{}) <-chan interface{} {
|
|
||||||
out := make(chan interface{})
|
|
||||||
go func() {
|
go func() {
|
||||||
select {
|
defer p.wg.Done()
|
||||||
case p, open := <-in:
|
|
||||||
if open {
|
|
||||||
out <- p
|
|
||||||
}
|
|
||||||
case <-ctx.Done():
|
|
||||||
}
|
|
||||||
|
|
||||||
close(out)
|
if ret, err := f(); err == nil {
|
||||||
for range in {
|
p.once.Do(func() {
|
||||||
|
p.result = ret
|
||||||
|
p.firstDone <- struct{}{}
|
||||||
|
if p.cancel != nil {
|
||||||
|
p.cancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return out
|
|
||||||
}
|
}
|
||||||
|
@ -4,41 +4,63 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func sleepAndSend(delay int, in chan<- interface{}, input interface{}) {
|
func sleepAndSend(ctx context.Context, delay int, input interface{}) func() (interface{}, error) {
|
||||||
time.Sleep(time.Millisecond * time.Duration(delay))
|
return func() (interface{}, error) {
|
||||||
in <- input
|
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
|
||||||
}
|
select {
|
||||||
|
case <-timer.C:
|
||||||
func sleepAndClose(delay int, in chan interface{}) {
|
return input, nil
|
||||||
time.Sleep(time.Millisecond * time.Duration(delay))
|
case <-ctx.Done():
|
||||||
close(in)
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPicker_Basic(t *testing.T) {
|
func TestPicker_Basic(t *testing.T) {
|
||||||
in := make(chan interface{})
|
picker, ctx := WithContext(context.Background())
|
||||||
fast := SelectFast(context.Background(), in)
|
picker.Go(sleepAndSend(ctx, 30, 2))
|
||||||
go sleepAndSend(20, in, 1)
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
go sleepAndSend(30, in, 2)
|
|
||||||
go sleepAndClose(40, in)
|
|
||||||
|
|
||||||
number, exist := <-fast
|
number := picker.Wait()
|
||||||
if !exist || number != 1 {
|
assert.NotNil(t, number)
|
||||||
t.Error("should recv 1", exist, number)
|
assert.Equal(t, number.(int), 1)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPicker_Timeout(t *testing.T) {
|
func TestPicker_Timeout(t *testing.T) {
|
||||||
in := make(chan interface{})
|
picker, ctx := WithTimeout(context.Background(), time.Millisecond*5)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
defer cancel()
|
|
||||||
fast := SelectFast(ctx, in)
|
|
||||||
go sleepAndSend(20, in, 1)
|
|
||||||
go sleepAndClose(30, in)
|
|
||||||
|
|
||||||
_, exist := <-fast
|
number := picker.Wait()
|
||||||
if exist {
|
assert.Nil(t, number)
|
||||||
t.Error("should recv false")
|
}
|
||||||
}
|
|
||||||
|
func TestPicker_WaitWithoutAutoCancel(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*60)
|
||||||
|
defer cancel()
|
||||||
|
picker := WithoutAutoCancel(ctx)
|
||||||
|
|
||||||
|
trigger := false
|
||||||
|
picker.Go(sleepAndSend(ctx, 10, 1))
|
||||||
|
picker.Go(func() (interface{}, error) {
|
||||||
|
timer := time.NewTimer(time.Millisecond * time.Duration(30))
|
||||||
|
select {
|
||||||
|
case <-timer.C:
|
||||||
|
trigger = true
|
||||||
|
return 2, nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
elm := picker.WaitWithoutCancel()
|
||||||
|
|
||||||
|
assert.NotNil(t, elm)
|
||||||
|
assert.Equal(t, elm.(int), 1)
|
||||||
|
|
||||||
|
elm = picker.Wait()
|
||||||
|
assert.True(t, trigger)
|
||||||
|
assert.Equal(t, elm.(int), 1)
|
||||||
}
|
}
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
@ -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,10 @@ 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)
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("type %s not support", val.Kind().String())
|
return fmt.Errorf("type %s not support", val.Kind().String())
|
||||||
}
|
}
|
||||||
@ -108,7 +114,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 +131,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 +164,76 @@ 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()
|
||||||
|
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) 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
|
||||||
|
}
|
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")
|
||||||
|
}
|
||||||
|
}
|
117
component/fakeip/pool.go
Normal file
117
component/fakeip/pool.go
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
package fakeip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Pool is a implementation about fake ip generator without storage
|
||||||
|
type Pool struct {
|
||||||
|
max uint32
|
||||||
|
min uint32
|
||||||
|
gateway uint32
|
||||||
|
offset uint32
|
||||||
|
mux *sync.Mutex
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) (*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,
|
||||||
|
mux: &sync.Mutex{},
|
||||||
|
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)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
assert.Error(t, err)
|
||||||
|
}
|
46
component/nat/table.go
Normal file
46
component/nat/table.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package nat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Table struct {
|
||||||
|
mapping sync.Map
|
||||||
|
}
|
||||||
|
|
||||||
|
type element struct {
|
||||||
|
RemoteAddr net.Addr
|
||||||
|
RemoteConn net.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) Set(key string, pc net.PacketConn, addr net.Addr) {
|
||||||
|
// set conn read timeout
|
||||||
|
t.mapping.Store(key, &element{
|
||||||
|
RemoteConn: pc,
|
||||||
|
RemoteAddr: addr,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) Get(key string) (net.PacketConn, net.Addr) {
|
||||||
|
item, exist := t.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
elm := item.(*element)
|
||||||
|
return elm.RemoteConn, elm.RemoteAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
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{}
|
||||||
|
}
|
@ -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,8 +6,9 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@ -18,8 +19,6 @@ const (
|
|||||||
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
|
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, 2048) }}
|
|
||||||
|
|
||||||
// TLSObfs is shadowsocks tls simple-obfs implementation
|
// TLSObfs is shadowsocks tls simple-obfs implementation
|
||||||
type TLSObfs struct {
|
type TLSObfs struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
@ -30,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)
|
||||||
@ -103,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{}
|
||||||
@ -111,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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)}
|
||||||
|
}
|
375
component/socks5/socks5.go
Normal file
375
component/socks5/socks5.go
Normal file
@ -0,0 +1,375 @@
|
|||||||
|
package socks5
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
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 = 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,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))
|
||||||
@ -153,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)
|
||||||
@ -196,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,
|
||||||
@ -209,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,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@ -57,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
|
||||||
@ -69,22 +71,23 @@ type Client struct {
|
|||||||
security Security
|
security Security
|
||||||
tls bool
|
tls bool
|
||||||
host string
|
host string
|
||||||
wsConfig *websocketConfig
|
wsConfig *WebsocketConfig
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
HostName string
|
HostName string
|
||||||
Port string
|
Port string
|
||||||
NetWork string
|
NetWork string
|
||||||
WebSocketPath string
|
WebSocketPath string
|
||||||
SkipCertVerify bool
|
WebSocketHeaders map[string]string
|
||||||
SessionCacahe tls.ClientSessionCache
|
SkipCertVerify bool
|
||||||
|
SessionCache tls.ClientSessionCache
|
||||||
}
|
}
|
||||||
|
|
||||||
// New return a Conn with net.Conn and DstAddr
|
// New return a Conn with net.Conn and DstAddr
|
||||||
@ -92,14 +95,14 @@ func (c *Client) New(conn net.Conn, dst *DstAddr) (net.Conn, error) {
|
|||||||
var err error
|
var err error
|
||||||
r := rand.Intn(len(c.user))
|
r := rand.Intn(len(c.user))
|
||||||
if c.wsConfig != nil {
|
if c.wsConfig != nil {
|
||||||
conn, err = newWebsocketConn(conn, c.wsConfig)
|
conn, err = NewWebsocketConn(conn, c.wsConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else if c.tls {
|
} else if c.tls {
|
||||||
conn = tls.Client(conn, c.tlsConfig)
|
conn = tls.Client(conn, c.tlsConfig)
|
||||||
}
|
}
|
||||||
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
|
||||||
@ -130,6 +133,11 @@ 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)
|
host := net.JoinHostPort(config.HostName, config.Port)
|
||||||
|
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
@ -137,20 +145,24 @@ func NewClient(config Config) (*Client, error) {
|
|||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
ServerName: config.HostName,
|
ServerName: config.HostName,
|
||||||
InsecureSkipVerify: config.SkipCertVerify,
|
InsecureSkipVerify: config.SkipCertVerify,
|
||||||
ClientSessionCache: config.SessionCacahe,
|
ClientSessionCache: config.SessionCache,
|
||||||
}
|
}
|
||||||
if tlsConfig.ClientSessionCache == nil {
|
if tlsConfig.ClientSessionCache == nil {
|
||||||
tlsConfig.ClientSessionCache = getClientSessionCache()
|
tlsConfig.ClientSessionCache = getClientSessionCache()
|
||||||
}
|
}
|
||||||
|
if host := header.Get("Host"); host != "" {
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var wsConfig *websocketConfig
|
var wsConfig *WebsocketConfig
|
||||||
if config.NetWork == "ws" {
|
if config.NetWork == "ws" {
|
||||||
wsConfig = &websocketConfig{
|
wsConfig = &WebsocketConfig{
|
||||||
host: host,
|
Host: host,
|
||||||
path: config.WebSocketPath,
|
Path: config.WebSocketPath,
|
||||||
tls: config.TLS,
|
Headers: header,
|
||||||
tlsConfig: tlsConfig,
|
TLS: config.TLS,
|
||||||
|
TLSConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@ -18,11 +19,12 @@ type websocketConn struct {
|
|||||||
remoteAddr net.Addr
|
remoteAddr net.Addr
|
||||||
}
|
}
|
||||||
|
|
||||||
type websocketConfig struct {
|
type WebsocketConfig struct {
|
||||||
host string
|
Host string
|
||||||
path string
|
Path string
|
||||||
tls bool
|
Headers http.Header
|
||||||
tlsConfig *tls.Config
|
TLS bool
|
||||||
|
TLSConfig *tls.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read implements net.Conn.Read()
|
// Read implements net.Conn.Read()
|
||||||
@ -100,7 +102,7 @@ func (wsc *websocketConn) SetWriteDeadline(t time.Time) error {
|
|||||||
return wsc.conn.SetWriteDeadline(t)
|
return wsc.conn.SetWriteDeadline(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newWebsocketConn(conn net.Conn, c *websocketConfig) (net.Conn, error) {
|
func NewWebsocketConn(conn net.Conn, c *WebsocketConfig) (net.Conn, error) {
|
||||||
dialer := &websocket.Dialer{
|
dialer := &websocket.Dialer{
|
||||||
NetDial: func(network, addr string) (net.Conn, error) {
|
NetDial: func(network, addr string) (net.Conn, error) {
|
||||||
return conn, nil
|
return conn, nil
|
||||||
@ -111,25 +113,32 @@ func newWebsocketConn(conn net.Conn, c *websocketConfig) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
scheme := "ws"
|
scheme := "ws"
|
||||||
if c.tls {
|
if c.TLS {
|
||||||
scheme = "wss"
|
scheme = "wss"
|
||||||
dialer.TLSClientConfig = c.tlsConfig
|
dialer.TLSClientConfig = c.TLSConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
host, port, err := net.SplitHostPort(c.host)
|
host, port, _ := net.SplitHostPort(c.Host)
|
||||||
if (scheme == "ws" && port != "80") || (scheme == "wss" && port != "443") {
|
if (scheme == "ws" && port != "80") || (scheme == "wss" && port != "443") {
|
||||||
host = c.host
|
host = c.Host
|
||||||
}
|
}
|
||||||
|
|
||||||
uri := url.URL{
|
uri := url.URL{
|
||||||
Scheme: scheme,
|
Scheme: scheme,
|
||||||
Host: host,
|
Host: host,
|
||||||
Path: c.path,
|
Path: c.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
wsConn, resp, err := dialer.Dial(uri.String(), nil)
|
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 {
|
if err != nil {
|
||||||
var reason string
|
reason := err.Error()
|
||||||
if resp != nil {
|
if resp != nil {
|
||||||
reason = resp.Status
|
reason = resp.Status
|
||||||
}
|
}
|
||||||
|
383
config/config.go
383
config/config.go
@ -6,10 +6,14 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"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/dns"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
@ -24,79 +28,140 @@ type General struct {
|
|||||||
Port int `json:"port"`
|
Port int `json:"port"`
|
||||||
SocksPort int `json:"socks-port"`
|
SocksPort int `json:"socks-port"`
|
||||||
RedirPort int `json:"redir-port"`
|
RedirPort int `json:"redir-port"`
|
||||||
|
Authentication []string `json:"authentication"`
|
||||||
AllowLan bool `json:"allow-lan"`
|
AllowLan bool `json:"allow-lan"`
|
||||||
|
BindAddress string `json:"bind-address"`
|
||||||
Mode T.Mode `json:"mode"`
|
Mode T.Mode `json:"mode"`
|
||||||
LogLevel log.LogLevel `json:"log-level"`
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
ExternalController string `json:"external-controller,omitempty"`
|
ExternalController string `json:"-"`
|
||||||
Secret string `json:"secret,omitempty"`
|
ExternalUI string `json:"-"`
|
||||||
|
Secret string `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DNS config
|
// DNS config
|
||||||
type DNS struct {
|
type DNS struct {
|
||||||
Enable bool `yaml:"enable"`
|
Enable bool `yaml:"enable"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
NameServer []dns.NameServer `yaml:"nameserver"`
|
NameServer []dns.NameServer `yaml:"nameserver"`
|
||||||
Fallback []dns.NameServer `yaml:"fallback"`
|
Fallback []dns.NameServer `yaml:"fallback"`
|
||||||
Listen string `yaml:"listen"`
|
FallbackFilter FallbackFilter `yaml:"fallback-filter"`
|
||||||
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
Listen string `yaml:"listen"`
|
||||||
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
|
FakeIPRange *fakeip.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FallbackFilter config
|
||||||
|
type FallbackFilter struct {
|
||||||
|
GeoIP bool `yaml:"geoip"`
|
||||||
|
IPCIDR []*net.IPNet `yaml:"ipcidr"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Experimental config
|
||||||
|
type Experimental struct {
|
||||||
|
IgnoreResolveFail bool `yaml:"ignore-resolve-fail"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config is clash config manager
|
// Config is clash config manager
|
||||||
type Config struct {
|
type Config struct {
|
||||||
General *General
|
General *General
|
||||||
DNS *DNS
|
DNS *DNS
|
||||||
Rules []C.Rule
|
Experimental *Experimental
|
||||||
Proxies map[string]C.Proxy
|
Hosts *trie.Trie
|
||||||
|
Rules []C.Rule
|
||||||
|
Users []auth.AuthUser
|
||||||
|
Proxies map[string]C.Proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
type rawDNS struct {
|
type rawDNS struct {
|
||||||
Enable bool `yaml:"enable"`
|
Enable bool `yaml:"enable"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
NameServer []string `yaml:"nameserver"`
|
NameServer []string `yaml:"nameserver"`
|
||||||
Fallback []string `yaml:"fallback"`
|
Fallback []string `yaml:"fallback"`
|
||||||
Listen string `yaml:"listen"`
|
FallbackFilter rawFallbackFilter `yaml:"fallback-filter"`
|
||||||
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
Listen string `yaml:"listen"`
|
||||||
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
|
FakeIPRange string `yaml:"fake-ip-range"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type rawFallbackFilter struct {
|
||||||
|
GeoIP bool `yaml:"geoip"`
|
||||||
|
IPCIDR []string `yaml:"ipcidr"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type rawConfig struct {
|
type rawConfig struct {
|
||||||
Port int `yaml:"port"`
|
Port int `yaml:"port"`
|
||||||
SocksPort int `yaml:"socks-port"`
|
SocksPort int `yaml:"socks-port"`
|
||||||
RedirPort int `yaml:"redir-port"`
|
RedirPort int `yaml:"redir-port"`
|
||||||
|
Authentication []string `yaml:"authentication"`
|
||||||
AllowLan bool `yaml:"allow-lan"`
|
AllowLan bool `yaml:"allow-lan"`
|
||||||
|
BindAddress string `yaml:"bind-address"`
|
||||||
Mode T.Mode `yaml:"mode"`
|
Mode T.Mode `yaml:"mode"`
|
||||||
LogLevel log.LogLevel `yaml:"log-level"`
|
LogLevel log.LogLevel `yaml:"log-level"`
|
||||||
ExternalController string `yaml:"external-controller"`
|
ExternalController string `yaml:"external-controller"`
|
||||||
|
ExternalUI string `yaml:"external-ui"`
|
||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
|
|
||||||
DNS *rawDNS `yaml:"dns"`
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
Proxy []map[string]interface{} `yaml:"Proxy"`
|
DNS rawDNS `yaml:"dns"`
|
||||||
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
Experimental Experimental `yaml:"experimental"`
|
||||||
Rule []string `yaml:"Rule"`
|
Proxy []map[string]interface{} `yaml:"Proxy"`
|
||||||
|
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
||||||
|
Rule []string `yaml:"Rule"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// forward compatibility before 1.0
|
||||||
|
func readRawConfig(path string) ([]byte, error) {
|
||||||
|
data, err := ioutil.ReadFile(path)
|
||||||
|
if err == nil && len(data) != 0 {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if filepath.Ext(path) != ".yaml" {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
path = path[:len(path)-5] + ".yml"
|
||||||
|
if _, err = os.Stat(path); err == nil {
|
||||||
|
return ioutil.ReadFile(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func readConfig(path string) (*rawConfig, error) {
|
func readConfig(path string) (*rawConfig, error) {
|
||||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
data, err := ioutil.ReadFile(path)
|
data, err := readRawConfig(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return nil, fmt.Errorf("Configuration file %s is empty", C.Path.Config())
|
return nil, fmt.Errorf("Configuration file %s is empty", path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// config with some default value
|
// config with some default value
|
||||||
rawConfig := &rawConfig{
|
rawConfig := &rawConfig{
|
||||||
AllowLan: false,
|
AllowLan: false,
|
||||||
Mode: T.Rule,
|
BindAddress: "*",
|
||||||
LogLevel: log.INFO,
|
Mode: T.Rule,
|
||||||
Rule: []string{},
|
Authentication: []string{},
|
||||||
Proxy: []map[string]interface{}{},
|
LogLevel: log.INFO,
|
||||||
ProxyGroup: []map[string]interface{}{},
|
Hosts: map[string]string{},
|
||||||
DNS: &rawDNS{
|
Rule: []string{},
|
||||||
Enable: false,
|
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{},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
||||||
@ -111,6 +176,7 @@ func Parse(path string) (*Config, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
config.Experimental = &rawCfg.Experimental
|
||||||
|
|
||||||
general, err := parseGeneral(rawCfg)
|
general, err := parseGeneral(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -124,7 +190,7 @@ func Parse(path string) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.Proxies = proxies
|
config.Proxies = proxies
|
||||||
|
|
||||||
rules, err := parseRules(rawCfg)
|
rules, err := parseRules(rawCfg, proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -136,6 +202,14 @@ func Parse(path string) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.DNS = dnsCfg
|
config.DNS = dnsCfg
|
||||||
|
|
||||||
|
hosts, err := parseHosts(rawCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Hosts = hosts
|
||||||
|
|
||||||
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -144,19 +218,33 @@ func parseGeneral(cfg *rawConfig) (*General, error) {
|
|||||||
socksPort := cfg.SocksPort
|
socksPort := cfg.SocksPort
|
||||||
redirPort := cfg.RedirPort
|
redirPort := cfg.RedirPort
|
||||||
allowLan := cfg.AllowLan
|
allowLan := cfg.AllowLan
|
||||||
|
bindAddress := cfg.BindAddress
|
||||||
externalController := cfg.ExternalController
|
externalController := cfg.ExternalController
|
||||||
|
externalUI := cfg.ExternalUI
|
||||||
secret := cfg.Secret
|
secret := cfg.Secret
|
||||||
mode := cfg.Mode
|
mode := cfg.Mode
|
||||||
logLevel := cfg.LogLevel
|
logLevel := cfg.LogLevel
|
||||||
|
|
||||||
|
if externalUI != "" {
|
||||||
|
if !filepath.IsAbs(externalUI) {
|
||||||
|
externalUI = filepath.Join(C.Path.HomeDir(), externalUI)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(externalUI); os.IsNotExist(err) {
|
||||||
|
return nil, fmt.Errorf("external-ui: %s not exist", externalUI)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
general := &General{
|
general := &General{
|
||||||
Port: port,
|
Port: port,
|
||||||
SocksPort: socksPort,
|
SocksPort: socksPort,
|
||||||
RedirPort: redirPort,
|
RedirPort: redirPort,
|
||||||
AllowLan: allowLan,
|
AllowLan: allowLan,
|
||||||
|
BindAddress: bindAddress,
|
||||||
Mode: mode,
|
Mode: mode,
|
||||||
LogLevel: logLevel,
|
LogLevel: logLevel,
|
||||||
ExternalController: externalController,
|
ExternalController: externalController,
|
||||||
|
ExternalUI: externalUI,
|
||||||
Secret: secret,
|
Secret: secret,
|
||||||
}
|
}
|
||||||
return general, nil
|
return general, nil
|
||||||
@ -164,13 +252,15 @@ func parseGeneral(cfg *rawConfig) (*General, error) {
|
|||||||
|
|
||||||
func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||||
proxies := make(map[string]C.Proxy)
|
proxies := make(map[string]C.Proxy)
|
||||||
|
proxyList := []string{}
|
||||||
proxiesConfig := cfg.Proxy
|
proxiesConfig := cfg.Proxy
|
||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
|
|
||||||
proxies["DIRECT"] = adapters.NewDirect()
|
proxies["DIRECT"] = adapters.NewProxy(adapters.NewDirect())
|
||||||
proxies["REJECT"] = adapters.NewReject()
|
proxies["REJECT"] = adapters.NewProxy(adapters.NewReject())
|
||||||
|
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||||
|
|
||||||
// parse proxy
|
// parse proxy
|
||||||
for idx, mapping := range proxiesConfig {
|
for idx, mapping := range proxiesConfig {
|
||||||
@ -179,8 +269,8 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
return nil, fmt.Errorf("Proxy %d missing type", idx)
|
return nil, fmt.Errorf("Proxy %d missing type", idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
var proxy C.Proxy
|
var proxy C.ProxyAdapter
|
||||||
var err error
|
err := fmt.Errorf("cannot parse")
|
||||||
switch proxyType {
|
switch proxyType {
|
||||||
case "ss":
|
case "ss":
|
||||||
ssOption := &adapters.ShadowSocksOption{}
|
ssOption := &adapters.ShadowSocksOption{}
|
||||||
@ -210,6 +300,13 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = adapters.NewVmess(*vmessOption)
|
proxy, err = adapters.NewVmess(*vmessOption)
|
||||||
|
case "snell":
|
||||||
|
snellOption := &adapters.SnellOption{}
|
||||||
|
err = decoder.Decode(mapping, snellOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = adapters.NewSnell(*snellOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
@ -221,22 +318,39 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
if _, exist := proxies[proxy.Name()]; exist {
|
if _, exist := proxies[proxy.Name()]; exist {
|
||||||
return nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
return nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
||||||
}
|
}
|
||||||
proxies[proxy.Name()] = proxy
|
proxies[proxy.Name()] = adapters.NewProxy(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, fmt.Errorf("ProxyGroup %d: missing name", idx)
|
||||||
|
}
|
||||||
|
proxyList = append(proxyList, groupName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if any loop exists and sort the ProxyGroups
|
||||||
|
if err := proxyGroupsDagSort(groupsConfig, decoder); err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse proxy group
|
// parse proxy group
|
||||||
for idx, mapping := range groupsConfig {
|
for _, mapping := range groupsConfig {
|
||||||
groupType, existType := mapping["type"].(string)
|
groupType, existType := mapping["type"].(string)
|
||||||
groupName, existName := mapping["name"].(string)
|
groupName, _ := mapping["name"].(string)
|
||||||
if !existType && existName {
|
if !existType {
|
||||||
return nil, fmt.Errorf("ProxyGroup %d: missing type or name", idx)
|
return nil, fmt.Errorf("ProxyGroup %s: missing type", groupName)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, exist := proxies[groupName]; exist {
|
if _, exist := proxies[groupName]; exist {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
return nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
||||||
}
|
}
|
||||||
var group C.Proxy
|
var group C.ProxyAdapter
|
||||||
var err error
|
ps := []C.Proxy{}
|
||||||
|
|
||||||
|
err := fmt.Errorf("cannot parse")
|
||||||
switch groupType {
|
switch groupType {
|
||||||
case "url-test":
|
case "url-test":
|
||||||
urlTestOption := &adapters.URLTestOption{}
|
urlTestOption := &adapters.URLTestOption{}
|
||||||
@ -245,7 +359,7 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
ps, err := getProxies(proxies, urlTestOption.Proxies)
|
ps, err = getProxies(proxies, urlTestOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
}
|
}
|
||||||
@ -257,7 +371,7 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
ps, err := getProxies(proxies, selectorOption.Proxies)
|
ps, err = getProxies(proxies, selectorOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
}
|
}
|
||||||
@ -269,28 +383,41 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
ps, err := getProxies(proxies, fallbackOption.Proxies)
|
ps, err = getProxies(proxies, fallbackOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
}
|
}
|
||||||
group, err = adapters.NewFallback(*fallbackOption, ps)
|
group, err = adapters.NewFallback(*fallbackOption, ps)
|
||||||
|
case "load-balance":
|
||||||
|
loadBalanceOption := &adapters.LoadBalanceOption{}
|
||||||
|
err = decoder.Decode(mapping, loadBalanceOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
ps, err = getProxies(proxies, loadBalanceOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
|
}
|
||||||
|
group, err = adapters.NewLoadBalance(*loadBalanceOption, ps)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("Proxy %s: %s", groupName, err.Error())
|
return nil, fmt.Errorf("Proxy %s: %s", groupName, err.Error())
|
||||||
}
|
}
|
||||||
proxies[groupName] = group
|
proxies[groupName] = adapters.NewProxy(group)
|
||||||
}
|
}
|
||||||
|
|
||||||
var ps []C.Proxy
|
ps := []C.Proxy{}
|
||||||
for _, v := range proxies {
|
for _, v := range proxyList {
|
||||||
ps = append(ps, v)
|
ps = append(ps, proxies[v])
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies["GLOBAL"], _ = adapters.NewSelector("GLOBAL", ps)
|
global, _ := adapters.NewSelector("GLOBAL", ps)
|
||||||
|
proxies["GLOBAL"] = adapters.NewProxy(global)
|
||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(cfg *rawConfig) ([]C.Rule, 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
|
||||||
@ -309,31 +436,75 @@ func parseRules(cfg *rawConfig) ([]C.Rule, error) {
|
|||||||
payload = rule[1]
|
payload = rule[1]
|
||||||
target = rule[2]
|
target = rule[2]
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("Rules[%d] error: format invalid", idx)
|
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)
|
||||||
|
var parsed C.Rule
|
||||||
switch rule[0] {
|
switch rule[0] {
|
||||||
case "DOMAIN":
|
case "DOMAIN":
|
||||||
rules = append(rules, R.NewDomain(payload, target))
|
parsed = R.NewDomain(payload, target)
|
||||||
case "DOMAIN-SUFFIX":
|
case "DOMAIN-SUFFIX":
|
||||||
rules = append(rules, R.NewDomainSuffix(payload, target))
|
parsed = R.NewDomainSuffix(payload, target)
|
||||||
case "DOMAIN-KEYWORD":
|
case "DOMAIN-KEYWORD":
|
||||||
rules = append(rules, R.NewDomainKeyword(payload, target))
|
parsed = R.NewDomainKeyword(payload, target)
|
||||||
case "GEOIP":
|
case "GEOIP":
|
||||||
rules = append(rules, R.NewGEOIP(payload, target))
|
parsed = R.NewGEOIP(payload, target)
|
||||||
case "IP-CIDR", "IP-CIDR6":
|
case "IP-CIDR", "IP-CIDR6":
|
||||||
rules = append(rules, R.NewIPCIDR(payload, target))
|
if rule := R.NewIPCIDR(payload, target, false); rule != nil {
|
||||||
|
parsed = rule
|
||||||
|
}
|
||||||
|
// deprecated when bump to 1.0
|
||||||
|
case "SOURCE-IP-CIDR":
|
||||||
|
fallthrough
|
||||||
|
case "SRC-IP-CIDR":
|
||||||
|
if rule := R.NewIPCIDR(payload, target, true); rule != nil {
|
||||||
|
parsed = rule
|
||||||
|
}
|
||||||
|
case "SRC-PORT":
|
||||||
|
if rule := R.NewPort(payload, target, true); rule != nil {
|
||||||
|
parsed = rule
|
||||||
|
}
|
||||||
|
case "DST-PORT":
|
||||||
|
if rule := R.NewPort(payload, target, false); rule != nil {
|
||||||
|
parsed = rule
|
||||||
|
}
|
||||||
case "MATCH":
|
case "MATCH":
|
||||||
fallthrough
|
fallthrough
|
||||||
|
// deprecated when bump to 1.0
|
||||||
case "FINAL":
|
case "FINAL":
|
||||||
rules = append(rules, R.NewFinal(target))
|
parsed = R.NewMatch(target)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if parsed == nil {
|
||||||
|
return nil, fmt.Errorf("Rules[%d] [%s] error: payload invalid", idx, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
rules = append(rules, parsed)
|
||||||
}
|
}
|
||||||
|
|
||||||
return rules, nil
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tree, nil
|
||||||
|
}
|
||||||
|
|
||||||
func hostWithDefaultPort(host string, defPort string) (string, error) {
|
func hostWithDefaultPort(host string, defPort string) (string, error) {
|
||||||
if !strings.Contains(host, ":") {
|
if !strings.Contains(host, ":") {
|
||||||
host += ":"
|
host += ":"
|
||||||
@ -353,41 +524,66 @@ func hostWithDefaultPort(host string, defPort string) (string, error) {
|
|||||||
|
|
||||||
func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
||||||
nameservers := []dns.NameServer{}
|
nameservers := []dns.NameServer{}
|
||||||
log.Debugln("%#v", servers)
|
|
||||||
|
|
||||||
for idx, server := range servers {
|
for idx, server := range servers {
|
||||||
// parse without scheme .e.g 8.8.8.8:53
|
// parse without scheme .e.g 8.8.8.8:53
|
||||||
if host, err := hostWithDefaultPort(server, "53"); err == nil {
|
if !strings.Contains(server, "://") {
|
||||||
nameservers = append(
|
server = "udp://" + server
|
||||||
nameservers,
|
|
||||||
dns.NameServer{Addr: host},
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
|
||||||
u, err := url.Parse(server)
|
u, err := url.Parse(server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if u.Scheme != "tls" {
|
var host, dnsNetType string
|
||||||
|
switch u.Scheme {
|
||||||
|
case "udp":
|
||||||
|
host, err = hostWithDefaultPort(u.Host, "53")
|
||||||
|
dnsNetType = "" // UDP
|
||||||
|
case "tcp":
|
||||||
|
host, err = hostWithDefaultPort(u.Host, "53")
|
||||||
|
dnsNetType = "tcp" // TCP
|
||||||
|
case "tls":
|
||||||
|
host, err = hostWithDefaultPort(u.Host, "853")
|
||||||
|
dnsNetType = "tcp-tls" // DNS over TLS
|
||||||
|
case "https":
|
||||||
|
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path}
|
||||||
|
host = clearURL.String()
|
||||||
|
dnsNetType = "https" // DNS over HTTPS
|
||||||
|
default:
|
||||||
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||||
}
|
}
|
||||||
|
|
||||||
host, err := hostWithDefaultPort(u.Host, "853")
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
nameservers = append(
|
nameservers = append(
|
||||||
nameservers,
|
nameservers,
|
||||||
dns.NameServer{
|
dns.NameServer{
|
||||||
Net: "tcp-tls",
|
Net: dnsNetType,
|
||||||
Addr: host,
|
Addr: host,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nameservers, nil
|
return nameservers, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDNS(cfg *rawDNS) (*DNS, error) {
|
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 {
|
if cfg.Enable && len(cfg.NameServer) == 0 {
|
||||||
return nil, fmt.Errorf("If DNS configuration is turned on, NameServer cannot be empty")
|
return nil, fmt.Errorf("If DNS configuration is turned on, NameServer cannot be empty")
|
||||||
}
|
}
|
||||||
@ -395,16 +591,49 @@ func parseDNS(cfg *rawDNS) (*DNS, error) {
|
|||||||
dnsCfg := &DNS{
|
dnsCfg := &DNS{
|
||||||
Enable: cfg.Enable,
|
Enable: cfg.Enable,
|
||||||
Listen: cfg.Listen,
|
Listen: cfg.Listen,
|
||||||
|
IPv6: cfg.IPv6,
|
||||||
EnhancedMode: cfg.EnhancedMode,
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
|
FallbackFilter: FallbackFilter{
|
||||||
|
IPCIDR: []*net.IPNet{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer); err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if nameserver, err := parseNameServer(cfg.NameServer); err == nil {
|
if dnsCfg.Fallback, err = parseNameServer(cfg.Fallback); err != nil {
|
||||||
dnsCfg.NameServer = nameserver
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if fallback, err := parseNameServer(cfg.Fallback); err == nil {
|
if cfg.EnhancedMode == dns.FAKEIP {
|
||||||
dnsCfg.Fallback = fallback
|
_, ipnet, err := net.ParseCIDR(cfg.FakeIPRange)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pool, err := fakeip.New(ipnet, 1000)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsCfg.FakeIPRange = pool
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsCfg.FallbackFilter.GeoIP = cfg.FallbackFilter.GeoIP
|
||||||
|
if fallbackip, err := parseFallbackIPCIDR(cfg.FallbackFilter.IPCIDR); err == nil {
|
||||||
|
dnsCfg.FallbackFilter.IPCIDR = fallbackip
|
||||||
}
|
}
|
||||||
|
|
||||||
return dnsCfg, nil
|
return dnsCfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
||||||
|
users := make([]auth.AuthUser, 0)
|
||||||
|
for _, line := range rawRecords {
|
||||||
|
userData := strings.SplitN(line, ":", 2)
|
||||||
|
if len(userData) == 2 {
|
||||||
|
users = append(users, auth.AuthUser{User: userData[0], Pass: userData[1]})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return users
|
||||||
|
}
|
||||||
|
@ -63,9 +63,9 @@ func Init(dir string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// initial config.yml
|
// 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.Info("Can't find config, create an empty file")
|
||||||
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
123
config/utils.go
123
config/utils.go
@ -4,6 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -34,3 +36,124 @@ 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{}, decoder *structure.Decoder) 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
|
||||||
|
from []string
|
||||||
|
}
|
||||||
|
|
||||||
|
graph := make(map[string]*graphNode)
|
||||||
|
|
||||||
|
// Step 1.1 build dependency graph
|
||||||
|
for _, mapping := range groupsConfig {
|
||||||
|
option := &adapters.ProxyGroupOption{}
|
||||||
|
err := decoder.Decode(mapping, option)
|
||||||
|
groupName := option.Name
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if node, ok := graph[groupName]; ok {
|
||||||
|
if node.data != nil {
|
||||||
|
return fmt.Errorf("ProxyGroup %s: duplicate group name", groupName)
|
||||||
|
}
|
||||||
|
node.data = mapping
|
||||||
|
} else {
|
||||||
|
graph[groupName] = &graphNode{0, -1, mapping, 0, nil}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range option.Proxies {
|
||||||
|
if node, ex := graph[proxy]; ex {
|
||||||
|
node.indegree++
|
||||||
|
} else {
|
||||||
|
graph[proxy] = &graphNode{1, -1, nil, 0, 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.data != nil {
|
||||||
|
index++
|
||||||
|
groupsConfig[len(groupsConfig)-index] = node.data
|
||||||
|
for _, proxy := range node.data["proxies"].([]interface{}) {
|
||||||
|
child := graph[proxy.(string)]
|
||||||
|
child.indegree--
|
||||||
|
if child.indegree == 0 {
|
||||||
|
queue = append(queue, proxy.(string))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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.data == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, proxy := range node.data["proxies"].([]interface{}) {
|
||||||
|
node.outdegree++
|
||||||
|
child := graph[proxy.(string)]
|
||||||
|
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,7 +1,10 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Adapter Type
|
// Adapter Type
|
||||||
@ -11,27 +14,69 @@ const (
|
|||||||
Reject
|
Reject
|
||||||
Selector
|
Selector
|
||||||
Shadowsocks
|
Shadowsocks
|
||||||
|
Snell
|
||||||
Socks5
|
Socks5
|
||||||
Http
|
Http
|
||||||
URLTest
|
URLTest
|
||||||
Vmess
|
Vmess
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyAdapter interface {
|
||||||
|
Name() string
|
||||||
|
Type() AdapterType
|
||||||
|
DialContext(ctx context.Context, metadata *Metadata) (Conn, error)
|
||||||
|
DialUDP(metadata *Metadata) (PacketConn, net.Addr, error)
|
||||||
|
SupportUDP() bool
|
||||||
|
Destroy()
|
||||||
|
MarshalJSON() ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
MarshalJSON() ([]byte, error)
|
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
|
||||||
@ -49,6 +94,8 @@ func (at AdapterType) String() string {
|
|||||||
return "Selector"
|
return "Selector"
|
||||||
case Shadowsocks:
|
case Shadowsocks:
|
||||||
return "Shadowsocks"
|
return "Shadowsocks"
|
||||||
|
case Snell:
|
||||||
|
return "Snell"
|
||||||
case Socks5:
|
case Socks5:
|
||||||
return "Socks5"
|
return "Socks5"
|
||||||
case Http:
|
case Http:
|
||||||
@ -57,7 +104,9 @@ func (at AdapterType) String() string {
|
|||||||
return "URLTest"
|
return "URLTest"
|
||||||
case Vmess:
|
case Vmess:
|
||||||
return "Vmess"
|
return "Vmess"
|
||||||
|
case LoadBalance:
|
||||||
|
return "LoadBalance"
|
||||||
default:
|
default:
|
||||||
return "Unknow"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ const (
|
|||||||
TCP NetWork = iota
|
TCP NetWork = iota
|
||||||
UDP
|
UDP
|
||||||
|
|
||||||
HTTP SourceType = iota
|
HTTP Type = iota
|
||||||
SOCKS
|
SOCKS
|
||||||
REDIR
|
REDIR
|
||||||
)
|
)
|
||||||
@ -27,21 +27,34 @@ func (n *NetWork) String() string {
|
|||||||
return "udp"
|
return "udp"
|
||||||
}
|
}
|
||||||
|
|
||||||
type SourceType int
|
type Type int
|
||||||
|
|
||||||
// Metadata is used to store connection address
|
// Metadata is used to store connection address
|
||||||
type Metadata struct {
|
type Metadata struct {
|
||||||
NetWork NetWork
|
NetWork NetWork
|
||||||
Source SourceType
|
Type Type
|
||||||
|
SrcIP *net.IP
|
||||||
|
DstIP *net.IP
|
||||||
|
SrcPort string
|
||||||
|
DstPort string
|
||||||
AddrType int
|
AddrType int
|
||||||
Host string
|
Host string
|
||||||
IP *net.IP
|
|
||||||
Port string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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) 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,7 +2,6 @@ package constant
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"os/user"
|
|
||||||
P "path"
|
P "path"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -16,17 +15,11 @@ type path struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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)
|
homedir = P.Join(homedir, ".config", Name)
|
||||||
Path = &path{homedir: homedir}
|
Path = &path{homedir: homedir}
|
||||||
}
|
}
|
||||||
@ -41,7 +34,7 @@ func (p *path) HomeDir() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) Config() string {
|
func (p *path) Config() string {
|
||||||
return P.Join(p.homedir, "config.yml")
|
return P.Join(p.homedir, "config.yaml")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) MMDB() string {
|
func (p *path) MMDB() string {
|
||||||
|
@ -7,7 +7,10 @@ const (
|
|||||||
DomainKeyword
|
DomainKeyword
|
||||||
GEOIP
|
GEOIP
|
||||||
IPCIDR
|
IPCIDR
|
||||||
FINAL
|
SrcIPCIDR
|
||||||
|
SrcPort
|
||||||
|
DstPort
|
||||||
|
MATCH
|
||||||
)
|
)
|
||||||
|
|
||||||
type RuleType int
|
type RuleType int
|
||||||
@ -24,10 +27,16 @@ func (rt RuleType) String() string {
|
|||||||
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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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"
|
||||||
|
)
|
252
dns/client.go
252
dns/client.go
@ -2,258 +2,20 @@ package dns
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"github.com/Dreamacro/clash/common/picker"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
D "github.com/miekg/dns"
|
D "github.com/miekg/dns"
|
||||||
geoip2 "github.com/oschwald/geoip2-golang"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
type client struct {
|
||||||
globalSessionCache = tls.NewLRUClientSessionCache(64)
|
*D.Client
|
||||||
|
|
||||||
mmdb *geoip2.Reader
|
|
||||||
once sync.Once
|
|
||||||
resolver *Resolver
|
|
||||||
)
|
|
||||||
|
|
||||||
type Resolver struct {
|
|
||||||
ipv6 bool
|
|
||||||
mapping bool
|
|
||||||
fallback []*nameserver
|
|
||||||
main []*nameserver
|
|
||||||
cache *cache.Cache
|
|
||||||
}
|
|
||||||
|
|
||||||
type result struct {
|
|
||||||
Msg *D.Msg
|
|
||||||
Error error
|
|
||||||
}
|
|
||||||
|
|
||||||
func isIPRequest(q D.Question) bool {
|
|
||||||
if q.Qclass == D.ClassINET && (q.Qtype == D.TypeA || q.Qtype == D.TypeAAAA) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
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 := r.cache.Get(q.String())
|
|
||||||
if cache != nil {
|
|
||||||
return cache.(*D.Msg).Copy(), nil
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if msg != nil {
|
|
||||||
putMsgToCache(r.cache, q.String(), msg)
|
|
||||||
if r.mapping {
|
|
||||||
ips, err := r.msgToIP(msg)
|
|
||||||
if err != nil {
|
|
||||||
log.Debugln("[DNS] msg to ip error: %s", err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, ip := range ips {
|
|
||||||
putMsgToCache(r.cache, ip.String(), msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
isIPReq := isIPRequest(q)
|
|
||||||
if isIPReq {
|
|
||||||
msg, err = r.resolveIP(m)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
msg, err = r.exchange(r.main, m)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) exchange(servers []*nameserver, m *D.Msg) (msg *D.Msg, err error) {
|
|
||||||
in := make(chan interface{})
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
||||||
defer cancel()
|
|
||||||
fast := picker.SelectFast(ctx, in)
|
|
||||||
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(servers))
|
|
||||||
for _, server := range servers {
|
|
||||||
go func(s *nameserver) {
|
|
||||||
defer wg.Done()
|
|
||||||
msg, _, err := s.Client.Exchange(m, s.Address)
|
|
||||||
if err != nil || msg.Rcode != D.RcodeSuccess {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
in <- &result{Msg: msg, Error: err}
|
|
||||||
}(server)
|
|
||||||
}
|
|
||||||
|
|
||||||
// release in channel
|
|
||||||
go func() {
|
|
||||||
wg.Wait()
|
|
||||||
close(in)
|
|
||||||
}()
|
|
||||||
|
|
||||||
elm, exist := <-fast
|
|
||||||
if !exist {
|
|
||||||
return nil, errors.New("All DNS requests failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
resp := elm.(*result)
|
|
||||||
msg, err = resp.Msg, resp.Error
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) resolveIP(m *D.Msg) (msg *D.Msg, err error) {
|
|
||||||
msgCh := r.resolve(r.main, m)
|
|
||||||
if r.fallback == nil {
|
|
||||||
res := <-msgCh
|
|
||||||
msg, err = res.Msg, res.Error
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fallbackMsg := r.resolve(r.fallback, m)
|
|
||||||
res := <-msgCh
|
|
||||||
if res.Error == nil {
|
|
||||||
if mmdb == nil {
|
|
||||||
return nil, errors.New("GeoIP can't use")
|
|
||||||
}
|
|
||||||
|
|
||||||
ips, err := r.msgToIP(res.Msg)
|
|
||||||
if err == nil {
|
|
||||||
if record, _ := mmdb.Country(ips[0]); record.Country.IsoCode == "CN" || record.Country.IsoCode == "" {
|
|
||||||
// release channel
|
|
||||||
go func() { <-fallbackMsg }()
|
|
||||||
msg = res.Msg
|
|
||||||
return msg, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res = <-fallbackMsg
|
|
||||||
msg, err = res.Msg, res.Error
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) ResolveIP(host string) (ip net.IP, err error) {
|
|
||||||
query := &D.Msg{}
|
|
||||||
dnsType := D.TypeA
|
|
||||||
if r.ipv6 {
|
|
||||||
dnsType = D.TypeAAAA
|
|
||||||
}
|
|
||||||
query.SetQuestion(D.Fqdn(host), dnsType)
|
|
||||||
|
|
||||||
msg, err := r.Exchange(query)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ips []net.IP
|
|
||||||
ips, err = r.msgToIP(msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
ip = ips[0]
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) msgToIP(msg *D.Msg) ([]net.IP, error) {
|
|
||||||
var 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(ips) == 0 {
|
|
||||||
return nil, errors.New("Can't parse msg")
|
|
||||||
}
|
|
||||||
|
|
||||||
return ips, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Resolver) IPToHost(ip net.IP) (string, bool) {
|
|
||||||
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) resolve(client []*nameserver, msg *D.Msg) <-chan *result {
|
|
||||||
ch := make(chan *result)
|
|
||||||
go func() {
|
|
||||||
res, err := r.exchange(client, msg)
|
|
||||||
ch <- &result{Msg: res, Error: err}
|
|
||||||
}()
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
|
|
||||||
type NameServer struct {
|
|
||||||
Net string
|
|
||||||
Addr string
|
|
||||||
}
|
|
||||||
|
|
||||||
type nameserver struct {
|
|
||||||
Client *D.Client
|
|
||||||
Address string
|
Address string
|
||||||
}
|
}
|
||||||
|
|
||||||
type Config struct {
|
func (c *client) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||||
Main, Fallback []NameServer
|
return c.ExchangeContext(context.Background(), m)
|
||||||
IPv6 bool
|
|
||||||
EnhancedMode EnhancedMode
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func transform(servers []NameServer) []*nameserver {
|
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||||
var ret []*nameserver
|
msg, _, err = c.Client.ExchangeContext(ctx, m, c.Address)
|
||||||
for _, s := range servers {
|
return
|
||||||
ret = append(ret, &nameserver{
|
|
||||||
Client: &D.Client{
|
|
||||||
Net: s.Net,
|
|
||||||
TLSConfig: &tls.Config{
|
|
||||||
ClientSessionCache: globalSessionCache,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Address: s.Addr,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return ret
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(config Config) *Resolver {
|
|
||||||
once.Do(func() {
|
|
||||||
mmdb, _ = geoip2.Open(C.Path.MMDB())
|
|
||||||
})
|
|
||||||
|
|
||||||
println(config.EnhancedMode)
|
|
||||||
|
|
||||||
r := &Resolver{
|
|
||||||
main: transform(config.Main),
|
|
||||||
ipv6: config.IPv6,
|
|
||||||
cache: cache.New(time.Second * 60),
|
|
||||||
mapping: config.EnhancedMode == MAPPING,
|
|
||||||
}
|
|
||||||
if config.Fallback != nil {
|
|
||||||
r.fallback = transform(config.Fallback)
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}
|
}
|
||||||
|
75
dns/doh.go
Normal file
75
dns/doh.go
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// dotMimeType is the DoH mimetype that should be used.
|
||||||
|
dotMimeType = "application/dns-message"
|
||||||
|
|
||||||
|
// dotPath is the URL path that should be used.
|
||||||
|
dotPath = "/dns-query"
|
||||||
|
)
|
||||||
|
|
||||||
|
var dohTransport = &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{ClientSessionCache: globalSessionCache},
|
||||||
|
}
|
||||||
|
|
||||||
|
type dohClient struct {
|
||||||
|
url string
|
||||||
|
}
|
||||||
|
|
||||||
|
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: dohTransport}
|
||||||
|
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
|
||||||
|
}
|
26
dns/filters.go
Normal file
26
dns/filters.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
type fallbackFilter interface {
|
||||||
|
Match(net.IP) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type geoipFilter struct{}
|
||||||
|
|
||||||
|
func (gf *geoipFilter) Match(ip net.IP) bool {
|
||||||
|
if mmdb == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
record, _ := mmdb.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)
|
||||||
|
}
|
106
dns/iputil.go
Normal file
106
dns/iputil.go
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errIPNotFound = errors.New("cannot found ip")
|
||||||
|
errIPVersion = errors.New("ip version 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 {
|
||||||
|
if DefaultResolver.ipv6 {
|
||||||
|
return DefaultResolver.ResolveIP(host)
|
||||||
|
}
|
||||||
|
return DefaultResolver.ResolveIPv4(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
|
||||||
|
}
|
79
dns/middleware.go
Normal file
79
dns/middleware.go
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
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, ".")
|
||||||
|
|
||||||
|
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.SetReply(r)
|
||||||
|
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.SetReply(r)
|
||||||
|
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.IsFakeIP() {
|
||||||
|
middlewares = append(middlewares, withFakeIP(resolver.pool))
|
||||||
|
}
|
||||||
|
|
||||||
|
return compose(middlewares, withResolver(resolver))
|
||||||
|
}
|
317
dns/resolver.go
Normal file
317
dns/resolver.go
Normal file
@ -0,0 +1,317 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/common/picker"
|
||||||
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
|
"github.com/Dreamacro/clash/component/fakeip"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
geoip2 "github.com/oschwald/geoip2-golang"
|
||||||
|
"golang.org/x/sync/singleflight"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// DefaultResolver aim to resolve ip
|
||||||
|
DefaultResolver *Resolver
|
||||||
|
|
||||||
|
// DefaultHosts aim to resolve hosts
|
||||||
|
DefaultHosts = trie.New()
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalSessionCache = tls.NewLRUClientSessionCache(64)
|
||||||
|
|
||||||
|
mmdb *geoip2.Reader
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
type resolver 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 []resolver
|
||||||
|
fallback []resolver
|
||||||
|
fallbackFilters []fallbackFilter
|
||||||
|
group singleflight.Group
|
||||||
|
cache *cache.Cache
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveIP request with TypeA and TypeAAAA, priority return TypeAAAA
|
||||||
|
func (r *Resolver) ResolveIP(host string) (ip net.IP, err error) {
|
||||||
|
ch := make(chan net.IP)
|
||||||
|
go func() {
|
||||||
|
defer close(ch)
|
||||||
|
ip, err := r.resolveIP(host, D.TypeA)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ch <- ip
|
||||||
|
}()
|
||||||
|
|
||||||
|
ip, err = r.resolveIP(host, D.TypeAAAA)
|
||||||
|
if err == nil {
|
||||||
|
go func() {
|
||||||
|
<-ch
|
||||||
|
}()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ip, open := <-ch
|
||||||
|
if !open {
|
||||||
|
return nil, 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 {
|
||||||
|
msg, err := r.fallbackExchange(m)
|
||||||
|
return msg, err
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) IsFakeIP() bool {
|
||||||
|
return r.fakeip
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) batchExchange(clients []resolver, m *D.Msg) (msg *D.Msg, err error) {
|
||||||
|
fast, ctx := picker.WithTimeout(context.Background(), time.Second)
|
||||||
|
for _, client := range clients {
|
||||||
|
r := client
|
||||||
|
fast.Go(func() (interface{}, error) {
|
||||||
|
msg, err := r.ExchangeContext(ctx, m)
|
||||||
|
if err != nil || msg.Rcode != D.RcodeSuccess {
|
||||||
|
return nil, errors.New("resolve error")
|
||||||
|
}
|
||||||
|
return msg, 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]) {
|
||||||
|
go func() { <-fallbackMsg }()
|
||||||
|
msg = res.Msg
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
query := &D.Msg{}
|
||||||
|
query.SetQuestion(D.Fqdn(host), dnsType)
|
||||||
|
|
||||||
|
msg, err := r.Exchange(query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ips := r.msgToIP(msg)
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return nil, errIPNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
ip = ips[0]
|
||||||
|
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 []resolver, msg *D.Msg) <-chan *result {
|
||||||
|
ch := make(chan *result)
|
||||||
|
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
|
||||||
|
IPv6 bool
|
||||||
|
EnhancedMode EnhancedMode
|
||||||
|
FallbackFilter FallbackFilter
|
||||||
|
Pool *fakeip.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(config Config) *Resolver {
|
||||||
|
r := &Resolver{
|
||||||
|
ipv6: config.IPv6,
|
||||||
|
main: transform(config.Main),
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
fallbackFilters := []fallbackFilter{}
|
||||||
|
if config.FallbackFilter.GeoIP {
|
||||||
|
once.Do(func() {
|
||||||
|
mmdb, _ = geoip2.Open(C.Path.MMDB())
|
||||||
|
})
|
||||||
|
|
||||||
|
fallbackFilters = append(fallbackFilters, &geoipFilter{})
|
||||||
|
}
|
||||||
|
for _, ipnet := range config.FallbackFilter.IPCIDR {
|
||||||
|
fallbackFilters = append(fallbackFilters, &ipnetFilter{ipnet: ipnet})
|
||||||
|
}
|
||||||
|
r.fallbackFilters = fallbackFilters
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
@ -9,31 +9,38 @@ import (
|
|||||||
var (
|
var (
|
||||||
address string
|
address string
|
||||||
server = &Server{}
|
server = &Server{}
|
||||||
|
|
||||||
|
dnsDefaultTTL uint32 = 600
|
||||||
)
|
)
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
*D.Server
|
*D.Server
|
||||||
r *Resolver
|
handler handler
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
|
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
|
||||||
msg, err := s.r.Exchange(r)
|
if len(r.Question) == 0 {
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
D.HandleFailed(w, r)
|
D.HandleFailed(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
msg.SetReply(r)
|
|
||||||
w.WriteMsg(msg)
|
s.handler(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) setHandler(handler handler) {
|
||||||
|
s.handler = handler
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReCreateServer(addr string, resolver *Resolver) error {
|
func ReCreateServer(addr string, resolver *Resolver) error {
|
||||||
if server.Server != nil {
|
if addr == address && resolver != nil {
|
||||||
server.Shutdown()
|
handler := newHandler(resolver)
|
||||||
|
server.setHandler(handler)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if addr == address {
|
if server.Server != nil {
|
||||||
return nil
|
server.Shutdown()
|
||||||
|
address = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
_, port, err := net.SplitHostPort(addr)
|
_, port, err := net.SplitHostPort(addr)
|
||||||
@ -52,7 +59,8 @@ func ReCreateServer(addr string, resolver *Resolver) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
address = addr
|
address = addr
|
||||||
server = &Server{r: resolver}
|
handler := newHandler(resolver)
|
||||||
|
server = &Server{handler: handler}
|
||||||
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
|
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
|
62
dns/util.go
62
dns/util.go
@ -1,6 +1,7 @@
|
|||||||
package dns
|
package dns
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/tls"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
@ -70,7 +71,7 @@ func (e EnhancedMode) String() string {
|
|||||||
case NORMAL:
|
case NORMAL:
|
||||||
return "normal"
|
return "normal"
|
||||||
case FAKEIP:
|
case FAKEIP:
|
||||||
return "fakeip"
|
return "fake-ip"
|
||||||
case MAPPING:
|
case MAPPING:
|
||||||
return "redir-host"
|
return "redir-host"
|
||||||
default:
|
default:
|
||||||
@ -79,11 +80,62 @@ func (e EnhancedMode) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
|
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
|
||||||
if len(msg.Answer) == 0 {
|
var ttl time.Duration
|
||||||
log.Debugln("[DNS] answer length is zero: %#v", msg)
|
if len(msg.Answer) != 0 {
|
||||||
|
ttl = time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
||||||
|
} else if len(msg.Ns) != 0 {
|
||||||
|
ttl = time.Duration(msg.Ns[0].Header().Ttl) * time.Second
|
||||||
|
} else if len(msg.Extra) != 0 {
|
||||||
|
ttl = time.Duration(msg.Extra[0].Header().Ttl) * time.Second
|
||||||
|
} else {
|
||||||
|
log.Debugln("[DNS] response msg error: %#v", msg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ttl := time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
c.Put(key, msg.Copy(), ttl)
|
||||||
c.Put(key, msg, ttl)
|
}
|
||||||
|
|
||||||
|
func setMsgTTL(msg *D.Msg, ttl uint32) {
|
||||||
|
for _, answer := range msg.Answer {
|
||||||
|
answer.Header().Ttl = ttl
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ns := range msg.Ns {
|
||||||
|
ns.Header().Ttl = ttl
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, extra := range msg.Extra {
|
||||||
|
extra.Header().Ttl = ttl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isIPRequest(q D.Question) bool {
|
||||||
|
if q.Qclass == D.ClassINET && (q.Qtype == D.TypeA || q.Qtype == D.TypeAAAA) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func transform(servers []NameServer) []resolver {
|
||||||
|
ret := []resolver{}
|
||||||
|
for _, s := range servers {
|
||||||
|
if s.Net == "https" {
|
||||||
|
ret = append(ret, &dohClient{url: s.Addr})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = append(ret, &client{
|
||||||
|
Client: &D.Client{
|
||||||
|
Net: s.Net,
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
ClientSessionCache: globalSessionCache,
|
||||||
|
// alpn identifier, see https://tools.ietf.org/html/draft-hoffman-dprive-dns-tls-alpn-00#page-6
|
||||||
|
NextProtos: []string{"dns"},
|
||||||
|
},
|
||||||
|
UDPSize: 4096,
|
||||||
|
},
|
||||||
|
Address: s.Addr,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return ret
|
||||||
}
|
}
|
||||||
|
25
go.mod
25
go.mod
@ -1,20 +1,23 @@
|
|||||||
module github.com/Dreamacro/clash
|
module github.com/Dreamacro/clash
|
||||||
|
|
||||||
|
go 1.13
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Dreamacro/go-shadowsocks2 v0.1.2
|
github.com/Dreamacro/go-shadowsocks2 v0.1.5-0.20191012162057-46254afc8b68
|
||||||
github.com/eapache/queue v1.1.0 // indirect
|
github.com/eapache/queue v1.1.0 // indirect
|
||||||
github.com/go-chi/chi v3.3.3+incompatible
|
github.com/go-chi/chi v4.0.2+incompatible
|
||||||
github.com/go-chi/cors v1.0.0
|
github.com/go-chi/cors v1.0.0
|
||||||
github.com/go-chi/render v1.0.1
|
github.com/go-chi/render v1.0.1
|
||||||
github.com/gofrs/uuid v3.1.0+incompatible
|
github.com/gofrs/uuid v3.2.0+incompatible
|
||||||
github.com/gorilla/websocket v1.4.0
|
github.com/gorilla/websocket v1.4.1
|
||||||
github.com/miekg/dns v1.1.0
|
github.com/miekg/dns v1.1.22
|
||||||
github.com/oschwald/geoip2-golang v1.2.1
|
github.com/oschwald/geoip2-golang v1.3.0
|
||||||
github.com/oschwald/maxminddb-golang v1.3.0 // indirect
|
github.com/oschwald/maxminddb-golang v1.5.0 // indirect
|
||||||
github.com/sirupsen/logrus v1.2.0
|
github.com/sirupsen/logrus v1.4.2
|
||||||
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85
|
github.com/stretchr/testify v1.4.0
|
||||||
golang.org/x/net v0.0.0-20181108082009-03003ca0c849 // indirect
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect
|
golang.org/x/net v0.0.0-20191011234655-491137f69257
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e
|
||||||
gopkg.in/eapache/channels.v1 v1.1.0
|
gopkg.in/eapache/channels.v1 v1.1.0
|
||||||
gopkg.in/yaml.v2 v2.2.2
|
gopkg.in/yaml.v2 v2.2.2
|
||||||
)
|
)
|
||||||
|
76
go.sum
76
go.sum
@ -1,46 +1,70 @@
|
|||||||
github.com/Dreamacro/go-shadowsocks2 v0.1.2 h1:8KgWbwAw5PJF+i6F3tI2iW/Em9WDtAuDG4obot8bGLM=
|
github.com/Dreamacro/go-shadowsocks2 v0.1.5-0.20191012162057-46254afc8b68 h1:UBDLpj1IGVkUcUBuZWE6DmZApPTZcnmcV6AfyDN/yhg=
|
||||||
github.com/Dreamacro/go-shadowsocks2 v0.1.2/go.mod h1:J5YbNUiKtaD7EJmQ4O9ruUTY9+IgrflPgm63K1nUE0I=
|
github.com/Dreamacro/go-shadowsocks2 v0.1.5-0.20191012162057-46254afc8b68/go.mod h1:Y8obOtHDOqxMGHjPglfCiXZBKExOA9VL6I6sJagOwYM=
|
||||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY=
|
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY=
|
||||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
|
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
|
github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
|
||||||
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
|
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
|
||||||
github.com/go-chi/chi v3.3.3+incompatible h1:KHkmBEMNkwKuK4FdQL7N2wOeB9jnIx7jR5wsuSBEFI8=
|
github.com/go-chi/chi v4.0.2+incompatible h1:maB6vn6FqCxrpz4FqWdh4+lwpyZIQS7YEAUcHlgXVRs=
|
||||||
github.com/go-chi/chi v3.3.3+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
|
github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
|
||||||
github.com/go-chi/cors v1.0.0 h1:e6x8k7uWbUwYs+aXDoiUzeQFT6l0cygBYyNhD7/1Tg0=
|
github.com/go-chi/cors v1.0.0 h1:e6x8k7uWbUwYs+aXDoiUzeQFT6l0cygBYyNhD7/1Tg0=
|
||||||
github.com/go-chi/cors v1.0.0/go.mod h1:K2Yje0VW/SJzxiyMYu6iPQYa7hMjQX2i/F491VChg1I=
|
github.com/go-chi/cors v1.0.0/go.mod h1:K2Yje0VW/SJzxiyMYu6iPQYa7hMjQX2i/F491VChg1I=
|
||||||
github.com/go-chi/render v1.0.1 h1:4/5tis2cKaNdnv9zFLfXzcquC9HbeZgCnxGnKrltBS8=
|
github.com/go-chi/render v1.0.1 h1:4/5tis2cKaNdnv9zFLfXzcquC9HbeZgCnxGnKrltBS8=
|
||||||
github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1OvJns=
|
github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1OvJns=
|
||||||
github.com/gofrs/uuid v3.1.0+incompatible h1:q2rtkjaKT4YEr6E1kamy0Ha4RtepWlQBedyHx0uzKwA=
|
github.com/gofrs/uuid v3.2.0+incompatible h1:y12jRkkFxsd7GpqdSZ+/KCs/fJbqpEXSGd4+jfEaewE=
|
||||||
github.com/gofrs/uuid v3.1.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||||
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
|
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
|
||||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/miekg/dns v1.1.0 h1:yv9O9RJbvVFkvW8PKYqp4x7HQkc5RWwmUY/L8MdUaIg=
|
github.com/miekg/dns v1.1.22 h1:Jm64b3bO9kP43ddLjL2EY3Io6bmy1qGb9Xxz6TqS6rc=
|
||||||
github.com/miekg/dns v1.1.0/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
github.com/miekg/dns v1.1.22/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
|
||||||
github.com/oschwald/geoip2-golang v1.2.1 h1:3iz+jmeJc6fuCyWeKgtXSXu7+zvkxJbHFXkMT5FVebU=
|
github.com/oschwald/geoip2-golang v1.3.0 h1:D+Hsdos1NARPbzZ2aInUHZL+dApIzo8E0ErJVsWcku8=
|
||||||
github.com/oschwald/geoip2-golang v1.2.1/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
github.com/oschwald/geoip2-golang v1.3.0/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
||||||
github.com/oschwald/maxminddb-golang v1.3.0 h1:oTh8IBSj10S5JNlUDg5WjJ1QdBMdeaZIkPEVfESSWgE=
|
github.com/oschwald/maxminddb-golang v1.5.0 h1:rmyoIV6z2/s9TCJedUuDiKht2RN12LWJ1L7iRGtWY64=
|
||||||
github.com/oschwald/maxminddb-golang v1.3.0/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY=
|
github.com/oschwald/maxminddb-golang v1.5.0/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
|
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
|
||||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
|
||||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||||
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 h1:et7+NAX3lLIk5qUCTA9QelBjGE/NkhzYw/mhnr0s7nI=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/net v0.0.0-20181108082009-03003ca0c849 h1:FSqE2GGG7wzsYUsWiQ8MZrvEd1EOyU3NCF0AW3Wtltg=
|
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392 h1:ACG4HJsFiNMf47Y4PeRoebLNy/2lXT9EtprMuTFWt1M=
|
||||||
golang.org/x/net v0.0.0-20181108082009-03003ca0c849/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
||||||
golang.org/x/sys v0.0.0-20181005133103-4497e2df6f9e h1:EfdBzeKbFSvOjoIqSZcfS8wp0FBLokGBEs9lz1OtSg0=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/sys v0.0.0-20181005133103-4497e2df6f9e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
|
||||||
|
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20191011234655-491137f69257 h1:ry8e2D+cwaV6hk7lb3aRTjjZo24shrbK0e11QEOkTIg=
|
||||||
|
golang.org/x/net v0.0.0-20191011234655-491137f69257/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||||
|
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe h1:6fAMxZRR6sl1Uq8U61gxU+kPTs2tR8uOySCbBP7BN/M=
|
||||||
|
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/eapache/channels.v1 v1.1.0 h1:5bGAyKKvyCTWjSj7mhefG6Lc68VyN4MH1v8/7OoeeB4=
|
gopkg.in/eapache/channels.v1 v1.1.0 h1:5bGAyKKvyCTWjSj7mhefG6Lc68VyN4MH1v8/7OoeeB4=
|
||||||
|
@ -1,12 +1,14 @@
|
|||||||
package executor
|
package executor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
"github.com/Dreamacro/clash/config"
|
"github.com/Dreamacro/clash/config"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/dns"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
P "github.com/Dreamacro/clash/proxy"
|
P "github.com/Dreamacro/clash/proxy"
|
||||||
|
authStore "github.com/Dreamacro/clash/proxy/auth"
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -22,30 +24,45 @@ func ParseWithPath(path string) (*config.Config, error) {
|
|||||||
|
|
||||||
// ApplyConfig dispatch configure to all parts
|
// ApplyConfig dispatch configure to all parts
|
||||||
func ApplyConfig(cfg *config.Config, force bool) {
|
func ApplyConfig(cfg *config.Config, force bool) {
|
||||||
|
updateUsers(cfg.Users)
|
||||||
if force {
|
if force {
|
||||||
updateGeneral(cfg.General)
|
updateGeneral(cfg.General)
|
||||||
}
|
}
|
||||||
updateProxies(cfg.Proxies)
|
updateProxies(cfg.Proxies)
|
||||||
updateRules(cfg.Rules)
|
updateRules(cfg.Rules)
|
||||||
updateGeneral(cfg.General)
|
|
||||||
updateDNS(cfg.DNS)
|
updateDNS(cfg.DNS)
|
||||||
|
updateHosts(cfg.Hosts)
|
||||||
|
updateExperimental(cfg.Experimental)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetGeneral() *config.General {
|
func GetGeneral() *config.General {
|
||||||
ports := P.GetPorts()
|
ports := P.GetPorts()
|
||||||
return &config.General{
|
authenticator := []string{}
|
||||||
Port: ports.Port,
|
if auth := authStore.Authenticator(); auth != nil {
|
||||||
SocksPort: ports.SocksPort,
|
authenticator = auth.Users()
|
||||||
RedirPort: ports.RedirPort,
|
|
||||||
AllowLan: P.AllowLan(),
|
|
||||||
Mode: T.Instance().Mode(),
|
|
||||||
LogLevel: log.Level(),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
general := &config.General{
|
||||||
|
Port: ports.Port,
|
||||||
|
SocksPort: ports.SocksPort,
|
||||||
|
RedirPort: ports.RedirPort,
|
||||||
|
Authentication: authenticator,
|
||||||
|
AllowLan: P.AllowLan(),
|
||||||
|
BindAddress: P.BindAddress(),
|
||||||
|
Mode: T.Instance().Mode(),
|
||||||
|
LogLevel: log.Level(),
|
||||||
|
}
|
||||||
|
|
||||||
|
return general
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateExperimental(c *config.Experimental) {
|
||||||
|
T.Instance().UpdateExperimental(c.IgnoreResolveFail)
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateDNS(c *config.DNS) {
|
func updateDNS(c *config.DNS) {
|
||||||
if c.Enable == false {
|
if c.Enable == false {
|
||||||
T.Instance().SetResolver(nil)
|
dns.DefaultResolver = nil
|
||||||
dns.ReCreateServer("", nil)
|
dns.ReCreateServer("", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -54,23 +71,34 @@ func updateDNS(c *config.DNS) {
|
|||||||
Fallback: c.Fallback,
|
Fallback: c.Fallback,
|
||||||
IPv6: c.IPv6,
|
IPv6: c.IPv6,
|
||||||
EnhancedMode: c.EnhancedMode,
|
EnhancedMode: c.EnhancedMode,
|
||||||
|
Pool: c.FakeIPRange,
|
||||||
|
FallbackFilter: dns.FallbackFilter{
|
||||||
|
GeoIP: c.FallbackFilter.GeoIP,
|
||||||
|
IPCIDR: c.FallbackFilter.IPCIDR,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
T.Instance().SetResolver(r)
|
dns.DefaultResolver = r
|
||||||
dns.ReCreateServer(c.Listen, r)
|
if err := dns.ReCreateServer(c.Listen, r); err != nil {
|
||||||
|
log.Errorln("Start DNS server error: %s", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.Listen != "" {
|
||||||
|
log.Infoln("DNS server listening at: %s", c.Listen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateHosts(tree *trie.Trie) {
|
||||||
|
dns.DefaultHosts = tree
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateProxies(proxies map[string]C.Proxy) {
|
func updateProxies(proxies map[string]C.Proxy) {
|
||||||
tunnel := T.Instance()
|
tunnel := T.Instance()
|
||||||
oldProxies := tunnel.Proxies()
|
oldProxies := tunnel.Proxies()
|
||||||
|
|
||||||
// close old goroutine
|
// close proxy group goroutine
|
||||||
for _, proxy := range oldProxies {
|
for _, proxy := range oldProxies {
|
||||||
switch raw := proxy.(type) {
|
proxy.Destroy()
|
||||||
case *adapters.URLTest:
|
|
||||||
raw.Close()
|
|
||||||
case *adapters.Fallback:
|
|
||||||
raw.Close()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tunnel.UpdateProxies(proxies)
|
tunnel.UpdateProxies(proxies)
|
||||||
@ -85,8 +113,11 @@ func updateGeneral(general *config.General) {
|
|||||||
T.Instance().SetMode(general.Mode)
|
T.Instance().SetMode(general.Mode)
|
||||||
|
|
||||||
allowLan := general.AllowLan
|
allowLan := general.AllowLan
|
||||||
|
|
||||||
P.SetAllowLan(allowLan)
|
P.SetAllowLan(allowLan)
|
||||||
|
|
||||||
|
bindAddress := general.BindAddress
|
||||||
|
P.SetBindAddress(bindAddress)
|
||||||
|
|
||||||
if err := P.ReCreateHTTP(general.Port); err != nil {
|
if err := P.ReCreateHTTP(general.Port); err != nil {
|
||||||
log.Errorln("Start HTTP server error: %s", err.Error())
|
log.Errorln("Start HTTP server error: %s", err.Error())
|
||||||
}
|
}
|
||||||
@ -99,3 +130,11 @@ func updateGeneral(general *config.General) {
|
|||||||
log.Errorln("Start Redir server error: %s", err.Error())
|
log.Errorln("Start Redir server error: %s", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func updateUsers(users []auth.AuthUser) {
|
||||||
|
authenticator := auth.NewAuthenticator(users)
|
||||||
|
authStore.SetAuthenticator(authenticator)
|
||||||
|
if authenticator != nil {
|
||||||
|
log.Infoln("Authentication of local server updated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -12,6 +12,10 @@ func Parse() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.General.ExternalUI != "" {
|
||||||
|
route.SetUIPath(cfg.General.ExternalUI)
|
||||||
|
}
|
||||||
|
|
||||||
if cfg.General.ExternalController != "" {
|
if cfg.General.ExternalController != "" {
|
||||||
go route.Start(cfg.General.ExternalController, cfg.General.Secret)
|
go route.Start(cfg.General.ExternalController, cfg.General.Secret)
|
||||||
}
|
}
|
||||||
|
@ -22,17 +22,18 @@ func configRouter() http.Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type configSchema struct {
|
type configSchema struct {
|
||||||
Port *int `json:"port"`
|
Port *int `json:"port"`
|
||||||
SocksPort *int `json:"socket-port"`
|
SocksPort *int `json:"socks-port"`
|
||||||
RedirPort *int `json:"redir-port"`
|
RedirPort *int `json:"redir-port"`
|
||||||
AllowLan *bool `json:"allow-lan"`
|
AllowLan *bool `json:"allow-lan"`
|
||||||
Mode *T.Mode `json:"mode"`
|
BindAddress *string `json:"bind-address"`
|
||||||
LogLevel *log.LogLevel `json:"log-level"`
|
Mode *T.Mode `json:"mode"`
|
||||||
|
LogLevel *log.LogLevel `json:"log-level"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func getConfigs(w http.ResponseWriter, r *http.Request) {
|
func getConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
general := executor.GetGeneral()
|
general := executor.GetGeneral()
|
||||||
render.Respond(w, r, general)
|
render.JSON(w, r, general)
|
||||||
}
|
}
|
||||||
|
|
||||||
func pointerOrDefault(p *int, def int) int {
|
func pointerOrDefault(p *int, def int) int {
|
||||||
@ -46,8 +47,8 @@ func pointerOrDefault(p *int, def int) int {
|
|||||||
func patchConfigs(w http.ResponseWriter, r *http.Request) {
|
func patchConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
general := &configSchema{}
|
general := &configSchema{}
|
||||||
if err := render.DecodeJSON(r.Body, general); err != nil {
|
if err := render.DecodeJSON(r.Body, general); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, ErrBadRequest)
|
render.JSON(w, r, ErrBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,6 +56,10 @@ func patchConfigs(w http.ResponseWriter, r *http.Request) {
|
|||||||
P.SetAllowLan(*general.AllowLan)
|
P.SetAllowLan(*general.AllowLan)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if general.BindAddress != nil {
|
||||||
|
P.SetBindAddress(*general.BindAddress)
|
||||||
|
}
|
||||||
|
|
||||||
ports := P.GetPorts()
|
ports := P.GetPorts()
|
||||||
P.ReCreateHTTP(pointerOrDefault(general.Port, ports.Port))
|
P.ReCreateHTTP(pointerOrDefault(general.Port, ports.Port))
|
||||||
P.ReCreateSocks(pointerOrDefault(general.SocksPort, ports.SocksPort))
|
P.ReCreateSocks(pointerOrDefault(general.SocksPort, ports.SocksPort))
|
||||||
@ -68,7 +73,7 @@ func patchConfigs(w http.ResponseWriter, r *http.Request) {
|
|||||||
log.SetLevel(*general.LogLevel)
|
log.SetLevel(*general.LogLevel)
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
render.NoContent(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
type updateConfigRequest struct {
|
type updateConfigRequest struct {
|
||||||
@ -78,25 +83,25 @@ type updateConfigRequest struct {
|
|||||||
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
req := updateConfigRequest{}
|
req := updateConfigRequest{}
|
||||||
if err := render.DecodeJSON(r.Body, &req); err != nil {
|
if err := render.DecodeJSON(r.Body, &req); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, ErrBadRequest)
|
render.JSON(w, r, ErrBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !filepath.IsAbs(req.Path) {
|
if !filepath.IsAbs(req.Path) {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, newError("path is not a absoluted path"))
|
render.JSON(w, r, newError("path is not a absoluted path"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
force := r.URL.Query().Get("force") == "true"
|
force := r.URL.Query().Get("force") == "true"
|
||||||
cfg, err := executor.ParseWithPath(req.Path)
|
cfg, err := executor.ParseWithPath(req.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, newError(err.Error()))
|
render.JSON(w, r, newError(err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
executor.ApplyConfig(cfg, force)
|
executor.ApplyConfig(cfg, force)
|
||||||
w.WriteHeader(http.StatusNoContent)
|
render.NoContent(w, r)
|
||||||
}
|
}
|
||||||
|
@ -47,8 +47,8 @@ func findProxyByName(next http.Handler) http.Handler {
|
|||||||
proxies := T.Instance().Proxies()
|
proxies := T.Instance().Proxies()
|
||||||
proxy, exist := proxies[name]
|
proxy, exist := proxies[name]
|
||||||
if !exist {
|
if !exist {
|
||||||
w.WriteHeader(http.StatusNotFound)
|
render.Status(r, http.StatusNotFound)
|
||||||
render.Respond(w, r, ErrNotFound)
|
render.JSON(w, r, ErrNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,14 +59,14 @@ func findProxyByName(next http.Handler) http.Handler {
|
|||||||
|
|
||||||
func getProxies(w http.ResponseWriter, r *http.Request) {
|
func getProxies(w http.ResponseWriter, r *http.Request) {
|
||||||
proxies := T.Instance().Proxies()
|
proxies := T.Instance().Proxies()
|
||||||
render.Respond(w, r, map[string]map[string]C.Proxy{
|
render.JSON(w, r, render.M{
|
||||||
"proxies": proxies,
|
"proxies": proxies,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProxy(w http.ResponseWriter, r *http.Request) {
|
func getProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||||
render.Respond(w, r, proxy)
|
render.JSON(w, r, proxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateProxyRequest struct {
|
type UpdateProxyRequest struct {
|
||||||
@ -76,27 +76,26 @@ type UpdateProxyRequest struct {
|
|||||||
func updateProxy(w http.ResponseWriter, r *http.Request) {
|
func updateProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
req := UpdateProxyRequest{}
|
req := UpdateProxyRequest{}
|
||||||
if err := render.DecodeJSON(r.Body, &req); err != nil {
|
if err := render.DecodeJSON(r.Body, &req); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, ErrBadRequest)
|
render.JSON(w, r, ErrBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
proxy := r.Context().Value(CtxKeyProxy).(*A.Proxy)
|
||||||
|
selector, ok := proxy.ProxyAdapter.(*A.Selector)
|
||||||
selector, ok := proxy.(*A.Selector)
|
|
||||||
if !ok {
|
if !ok {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, ErrBadRequest)
|
render.JSON(w, r, newError("Must be a Selector"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := selector.Set(req.Name); err != nil {
|
if err := selector.Set(req.Name); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, newError(fmt.Sprintf("Selector update error: %s", err.Error())))
|
render.JSON(w, r, newError(fmt.Sprintf("Selector update error: %s", err.Error())))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
render.NoContent(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProxyDelay(w http.ResponseWriter, r *http.Request) {
|
func getProxyDelay(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -104,34 +103,30 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) {
|
|||||||
url := query.Get("url")
|
url := query.Get("url")
|
||||||
timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
|
timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, ErrBadRequest)
|
render.JSON(w, r, ErrBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||||
|
|
||||||
sigCh := make(chan int16)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
|
||||||
go func() {
|
defer cancel()
|
||||||
t, err := A.DelayTest(proxy, url)
|
|
||||||
if err != nil {
|
|
||||||
sigCh <- 0
|
|
||||||
}
|
|
||||||
sigCh <- t
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
delay, err := proxy.URLTest(ctx, url)
|
||||||
case <-time.After(time.Millisecond * time.Duration(timeout)):
|
if ctx.Err() != nil {
|
||||||
w.WriteHeader(http.StatusRequestTimeout)
|
render.Status(r, http.StatusGatewayTimeout)
|
||||||
render.Respond(w, r, ErrRequestTimeout)
|
render.JSON(w, r, ErrRequestTimeout)
|
||||||
case t := <-sigCh:
|
return
|
||||||
if t == 0 {
|
|
||||||
w.WriteHeader(http.StatusServiceUnavailable)
|
|
||||||
render.Respond(w, r, newError("An error occurred in the delay test"))
|
|
||||||
} else {
|
|
||||||
render.Respond(w, r, map[string]int16{
|
|
||||||
"delay": t,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err != nil || delay == 0 {
|
||||||
|
render.Status(r, http.StatusServiceUnavailable)
|
||||||
|
render.JSON(w, r, newError("An error occurred in the delay test"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
render.JSON(w, r, render.M{
|
||||||
|
"delay": delay,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ type Rule struct {
|
|||||||
func getRules(w http.ResponseWriter, r *http.Request) {
|
func getRules(w http.ResponseWriter, r *http.Request) {
|
||||||
rawRules := T.Instance().Rules()
|
rawRules := T.Instance().Rules()
|
||||||
|
|
||||||
var rules []Rule
|
rules := []Rule{}
|
||||||
for _, rule := range rawRules {
|
for _, rule := range rawRules {
|
||||||
rules = append(rules, Rule{
|
rules = append(rules, Rule{
|
||||||
Type: rule.RuleType().String(),
|
Type: rule.RuleType().String(),
|
||||||
@ -33,8 +33,7 @@ func getRules(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
render.JSON(w, r, render.M{
|
||||||
render.Respond(w, r, map[string][]Rule{
|
|
||||||
"rules": rules,
|
"rules": rules,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,33 @@
|
|||||||
package route
|
package route
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/go-chi/chi"
|
"github.com/go-chi/chi"
|
||||||
"github.com/go-chi/cors"
|
"github.com/go-chi/cors"
|
||||||
"github.com/go-chi/render"
|
"github.com/go-chi/render"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
serverSecret = ""
|
serverSecret = ""
|
||||||
serverAddr = ""
|
serverAddr = ""
|
||||||
|
|
||||||
|
uiPath = ""
|
||||||
|
|
||||||
|
upgrader = websocket.Upgrader{
|
||||||
|
CheckOrigin: func(r *http.Request) bool {
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
type Traffic struct {
|
type Traffic struct {
|
||||||
@ -24,6 +35,10 @@ type Traffic struct {
|
|||||||
Down int64 `json:"down"`
|
Down int64 `json:"down"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SetUIPath(path string) {
|
||||||
|
uiPath = path
|
||||||
|
}
|
||||||
|
|
||||||
func Start(addr string, secret string) {
|
func Start(addr string, secret string) {
|
||||||
if serverAddr != "" {
|
if serverAddr != "" {
|
||||||
return
|
return
|
||||||
@ -36,18 +51,33 @@ func Start(addr string, secret string) {
|
|||||||
|
|
||||||
cors := cors.New(cors.Options{
|
cors := cors.New(cors.Options{
|
||||||
AllowedOrigins: []string{"*"},
|
AllowedOrigins: []string{"*"},
|
||||||
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
|
||||||
AllowedHeaders: []string{"Content-Type", "Authorization"},
|
AllowedHeaders: []string{"Content-Type", "Authorization"},
|
||||||
MaxAge: 300,
|
MaxAge: 300,
|
||||||
})
|
})
|
||||||
|
|
||||||
r.Use(cors.Handler, authentication)
|
r.Use(cors.Handler)
|
||||||
|
r.Get("/", hello)
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(authentication)
|
||||||
|
|
||||||
r.With(jsonContentType).Get("/traffic", traffic)
|
r.Get("/logs", getLogs)
|
||||||
r.With(jsonContentType).Get("/logs", getLogs)
|
r.Get("/traffic", traffic)
|
||||||
r.Mount("/configs", configRouter())
|
r.Get("/version", version)
|
||||||
r.Mount("/proxies", proxyRouter())
|
r.Mount("/configs", configRouter())
|
||||||
r.Mount("/rules", ruleRouter())
|
r.Mount("/proxies", proxyRouter())
|
||||||
|
r.Mount("/rules", ruleRouter())
|
||||||
|
})
|
||||||
|
|
||||||
|
if uiPath != "" {
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
fs := http.StripPrefix("/ui", http.FileServer(http.Dir(uiPath)))
|
||||||
|
r.Get("/ui", http.RedirectHandler("/ui/", http.StatusTemporaryRedirect).ServeHTTP)
|
||||||
|
r.Get("/ui/*", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fs.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
log.Infoln("RESTful API listening at: %s", addr)
|
log.Infoln("RESTful API listening at: %s", addr)
|
||||||
err := http.ListenAndServe(addr, r)
|
err := http.ListenAndServe(addr, r)
|
||||||
@ -56,29 +86,33 @@ func Start(addr string, secret string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func jsonContentType(next http.Handler) http.Handler {
|
|
||||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
}
|
|
||||||
return http.HandlerFunc(fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func authentication(next http.Handler) http.Handler {
|
func authentication(next http.Handler) http.Handler {
|
||||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||||
header := r.Header.Get("Authorization")
|
|
||||||
text := strings.SplitN(header, " ", 2)
|
|
||||||
|
|
||||||
if serverSecret == "" {
|
if serverSecret == "" {
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Browser websocket not support custom header
|
||||||
|
if websocket.IsWebSocketUpgrade(r) && r.URL.Query().Get("token") != "" {
|
||||||
|
token := r.URL.Query().Get("token")
|
||||||
|
if token != serverSecret {
|
||||||
|
render.Status(r, http.StatusUnauthorized)
|
||||||
|
render.JSON(w, r, ErrUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
header := r.Header.Get("Authorization")
|
||||||
|
text := strings.SplitN(header, " ", 2)
|
||||||
|
|
||||||
hasUnvalidHeader := text[0] != "Bearer"
|
hasUnvalidHeader := text[0] != "Bearer"
|
||||||
hasUnvalidSecret := len(text) == 2 && text[1] != serverSecret
|
hasUnvalidSecret := len(text) == 2 && text[1] != serverSecret
|
||||||
if hasUnvalidHeader || hasUnvalidSecret {
|
if hasUnvalidHeader || hasUnvalidSecret {
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
render.Status(r, http.StatusUnauthorized)
|
||||||
render.Respond(w, r, ErrUnauthorized)
|
render.JSON(w, r, ErrUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
@ -86,20 +120,49 @@ func authentication(next http.Handler) http.Handler {
|
|||||||
return http.HandlerFunc(fn)
|
return http.HandlerFunc(fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func hello(w http.ResponseWriter, r *http.Request) {
|
||||||
|
render.JSON(w, r, render.M{"hello": "clash"})
|
||||||
|
}
|
||||||
|
|
||||||
func traffic(w http.ResponseWriter, r *http.Request) {
|
func traffic(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusOK)
|
var wsConn *websocket.Conn
|
||||||
|
if websocket.IsWebSocketUpgrade(r) {
|
||||||
|
var err error
|
||||||
|
wsConn, err = upgrader.Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if wsConn == nil {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
render.Status(r, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
tick := time.NewTicker(time.Second)
|
tick := time.NewTicker(time.Second)
|
||||||
t := T.Instance().Traffic()
|
t := T.Instance().Traffic()
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
var err error
|
||||||
for range tick.C {
|
for range tick.C {
|
||||||
|
buf.Reset()
|
||||||
up, down := t.Now()
|
up, down := t.Now()
|
||||||
if err := json.NewEncoder(w).Encode(Traffic{
|
if err := json.NewEncoder(buf).Encode(Traffic{
|
||||||
Up: up,
|
Up: up,
|
||||||
Down: down,
|
Down: down,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
w.(http.Flusher).Flush()
|
|
||||||
|
if wsConn == nil {
|
||||||
|
_, err = w.Write(buf.Bytes())
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
} else {
|
||||||
|
err = wsConn.WriteMessage(websocket.TextMessage, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,25 +179,56 @@ func getLogs(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
level, ok := log.LogLevelMapping[levelText]
|
level, ok := log.LogLevelMapping[levelText]
|
||||||
if !ok {
|
if !ok {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.Respond(w, r, ErrBadRequest)
|
render.JSON(w, r, ErrBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var wsConn *websocket.Conn
|
||||||
|
if websocket.IsWebSocketUpgrade(r) {
|
||||||
|
var err error
|
||||||
|
wsConn, err = upgrader.Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if wsConn == nil {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
render.Status(r, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
sub := log.Subscribe()
|
sub := log.Subscribe()
|
||||||
render.Status(r, http.StatusOK)
|
defer log.UnSubscribe(sub)
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
var err error
|
||||||
for elm := range sub {
|
for elm := range sub {
|
||||||
|
buf.Reset()
|
||||||
log := elm.(*log.Event)
|
log := elm.(*log.Event)
|
||||||
if log.LogLevel < level {
|
if log.LogLevel < level {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(Log{
|
if err := json.NewEncoder(buf).Encode(Log{
|
||||||
Type: log.Type(),
|
Type: log.Type(),
|
||||||
Payload: log.Payload,
|
Payload: log.Payload,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
w.(http.Flusher).Flush()
|
|
||||||
|
if wsConn == nil {
|
||||||
|
_, err = w.Write(buf.Bytes())
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
} else {
|
||||||
|
err = wsConn.WriteMessage(websocket.TextMessage, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func version(w http.ResponseWriter, r *http.Request) {
|
||||||
|
render.JSON(w, r, render.M{"version": C.Version})
|
||||||
|
}
|
||||||
|
@ -2,6 +2,7 @@ package log
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/observable"
|
"github.com/Dreamacro/clash/common/observable"
|
||||||
|
|
||||||
@ -15,6 +16,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
log.SetOutput(os.Stdout)
|
||||||
log.SetLevel(log.DebugLevel)
|
log.SetLevel(log.DebugLevel)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,6 +62,11 @@ func Subscribe() observable.Subscription {
|
|||||||
return sub
|
return sub
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func UnSubscribe(sub observable.Subscription) {
|
||||||
|
source.UnSubscribe(sub)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func Level() LogLevel {
|
func Level() LogLevel {
|
||||||
return level
|
return level
|
||||||
}
|
}
|
||||||
|
9
main.go
9
main.go
@ -2,9 +2,11 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
"flag"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/config"
|
"github.com/Dreamacro/clash/config"
|
||||||
@ -15,15 +17,22 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
version bool
|
||||||
homedir string
|
homedir string
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
flag.StringVar(&homedir, "d", "", "set configuration directory")
|
flag.StringVar(&homedir, "d", "", "set configuration directory")
|
||||||
|
flag.BoolVar(&version, "v", false, "show current version of clash")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if version {
|
||||||
|
fmt.Printf("Clash %s %s %s %s\n", C.Version, runtime.GOOS, runtime.GOARCH, C.BuildTime)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if homedir != "" {
|
if homedir != "" {
|
||||||
if !filepath.IsAbs(homedir) {
|
if !filepath.IsAbs(homedir) {
|
||||||
currentDir, _ := os.Getwd()
|
currentDir, _ := os.Getwd()
|
||||||
|
17
proxy/auth/auth.go
Normal file
17
proxy/auth/auth.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
authenticator auth.Authenticator
|
||||||
|
)
|
||||||
|
|
||||||
|
func Authenticator() auth.Authenticator {
|
||||||
|
return authenticator
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetAuthenticator(au auth.Authenticator) {
|
||||||
|
authenticator = au
|
||||||
|
}
|
@ -2,11 +2,17 @@ package http
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"encoding/base64"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/inbound"
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
authStore "github.com/Dreamacro/clash/proxy/auth"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -18,6 +24,7 @@ type HttpListener struct {
|
|||||||
net.Listener
|
net.Listener
|
||||||
address string
|
address string
|
||||||
closed bool
|
closed bool
|
||||||
|
cache *cache.Cache
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHttpProxy(addr string) (*HttpListener, error) {
|
func NewHttpProxy(addr string) (*HttpListener, error) {
|
||||||
@ -25,10 +32,11 @@ func NewHttpProxy(addr string) (*HttpListener, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
hl := &HttpListener{l, addr, false}
|
hl := &HttpListener{l, addr, false, cache.New(30 * time.Second)}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
log.Infoln("HTTP proxy listening at: %s", addr)
|
log.Infoln("HTTP proxy listening at: %s", addr)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
c, err := hl.Accept()
|
c, err := hl.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -37,7 +45,7 @@ func NewHttpProxy(addr string) (*HttpListener, error) {
|
|||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
go handleConn(c)
|
go handleConn(c, hl.cache)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@ -53,14 +61,40 @@ func (l *HttpListener) Address() string {
|
|||||||
return l.address
|
return l.address
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleConn(conn net.Conn) {
|
func canActivate(loginStr string, authenticator auth.Authenticator, cache *cache.Cache) (ret bool) {
|
||||||
|
if result := cache.Get(loginStr); result != nil {
|
||||||
|
ret = result.(bool)
|
||||||
|
}
|
||||||
|
loginData, err := base64.StdEncoding.DecodeString(loginStr)
|
||||||
|
login := strings.Split(string(loginData), ":")
|
||||||
|
ret = err == nil && len(login) == 2 && authenticator.Verify(login[0], login[1])
|
||||||
|
|
||||||
|
cache.Put(loginStr, ret, time.Minute)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleConn(conn net.Conn, cache *cache.Cache) {
|
||||||
br := bufio.NewReader(conn)
|
br := bufio.NewReader(conn)
|
||||||
request, err := http.ReadRequest(br)
|
request, err := http.ReadRequest(br)
|
||||||
if err != nil {
|
if err != nil || request.URL.Host == "" {
|
||||||
conn.Close()
|
conn.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
authenticator := authStore.Authenticator()
|
||||||
|
if authenticator != nil {
|
||||||
|
if authStrings := strings.Split(request.Header.Get("Proxy-Authorization"), " "); len(authStrings) != 2 {
|
||||||
|
_, err = conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\n\r\n"))
|
||||||
|
conn.Close()
|
||||||
|
return
|
||||||
|
} else if !canActivate(authStrings[1], authenticator, cache) {
|
||||||
|
conn.Write([]byte("HTTP/1.1 403 Forbidden\r\n\r\n"))
|
||||||
|
log.Infoln("Auth failed from %s", conn.RemoteAddr().String())
|
||||||
|
conn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if request.Method == http.MethodConnect {
|
if request.Method == http.MethodConnect {
|
||||||
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -11,11 +11,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
allowLan = false
|
allowLan = false
|
||||||
|
bindAddress = "*"
|
||||||
|
|
||||||
socksListener *socks.SockListener
|
socksListener *socks.SockListener
|
||||||
httpListener *http.HttpListener
|
socksUDPListener *socks.SockUDPListener
|
||||||
redirListener *redir.RedirListener
|
httpListener *http.HttpListener
|
||||||
|
redirListener *redir.RedirListener
|
||||||
)
|
)
|
||||||
|
|
||||||
type listener interface {
|
type listener interface {
|
||||||
@ -33,12 +35,20 @@ func AllowLan() bool {
|
|||||||
return allowLan
|
return allowLan
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BindAddress() string {
|
||||||
|
return bindAddress
|
||||||
|
}
|
||||||
|
|
||||||
func SetAllowLan(al bool) {
|
func SetAllowLan(al bool) {
|
||||||
allowLan = al
|
allowLan = al
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SetBindAddress(host string) {
|
||||||
|
bindAddress = host
|
||||||
|
}
|
||||||
|
|
||||||
func ReCreateHTTP(port int) error {
|
func ReCreateHTTP(port int) error {
|
||||||
addr := genAddr(port, allowLan)
|
addr := genAddr(bindAddress, port, allowLan)
|
||||||
|
|
||||||
if httpListener != nil {
|
if httpListener != nil {
|
||||||
if httpListener.Address() == addr {
|
if httpListener.Address() == addr {
|
||||||
@ -62,7 +72,7 @@ func ReCreateHTTP(port int) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ReCreateSocks(port int) error {
|
func ReCreateSocks(port int) error {
|
||||||
addr := genAddr(port, allowLan)
|
addr := genAddr(bindAddress, port, allowLan)
|
||||||
|
|
||||||
if socksListener != nil {
|
if socksListener != nil {
|
||||||
if socksListener.Address() == addr {
|
if socksListener.Address() == addr {
|
||||||
@ -82,11 +92,29 @@ func ReCreateSocks(port int) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return reCreateSocksUDP(addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func reCreateSocksUDP(addr string) error {
|
||||||
|
if socksUDPListener != nil {
|
||||||
|
if socksUDPListener.Address() == addr {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
socksUDPListener.Close()
|
||||||
|
socksUDPListener = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
socksUDPListener, err = socks.NewSocksUDPProxy(addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReCreateRedir(port int) error {
|
func ReCreateRedir(port int) error {
|
||||||
addr := genAddr(port, allowLan)
|
addr := genAddr(bindAddress, port, allowLan)
|
||||||
|
|
||||||
if redirListener != nil {
|
if redirListener != nil {
|
||||||
if redirListener.Address() == addr {
|
if redirListener.Address() == addr {
|
||||||
@ -142,9 +170,14 @@ func portIsZero(addr string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func genAddr(port int, allowLan bool) string {
|
func genAddr(host string, port int, allowLan bool) string {
|
||||||
if allowLan {
|
if allowLan {
|
||||||
return fmt.Sprintf(":%d", port)
|
if host == "*" {
|
||||||
|
return fmt.Sprintf(":%d", port)
|
||||||
|
} else {
|
||||||
|
return fmt.Sprintf("%s:%d", host, port)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Sprintf("127.0.0.1:%d", port)
|
return fmt.Sprintf("127.0.0.1:%d", port)
|
||||||
}
|
}
|
||||||
|
@ -59,5 +59,5 @@ func handleRedir(conn net.Conn) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||||
tun.Add(adapters.NewSocket(target, conn, C.REDIR))
|
tun.Add(adapters.NewSocket(target, conn, C.REDIR, C.TCP))
|
||||||
}
|
}
|
||||||
|
@ -5,10 +5,10 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parserPacket(c net.Conn) (socks.Addr, error) {
|
func parserPacket(c net.Conn) (socks5.Addr, error) {
|
||||||
const (
|
const (
|
||||||
PfInout = 0
|
PfInout = 0
|
||||||
PfIn = 1
|
PfIn = 1
|
||||||
@ -51,7 +51,7 @@ func parserPacket(c net.Conn) (socks.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr := make([]byte, 1+net.IPv4len+2)
|
addr := make([]byte, 1+net.IPv4len+2)
|
||||||
addr[0] = socks.AtypIPv4
|
addr[0] = socks5.AtypIPv4
|
||||||
copy(addr[1:1+net.IPv4len], nl.rdaddr[:4])
|
copy(addr[1:1+net.IPv4len], nl.rdaddr[:4])
|
||||||
copy(addr[1+net.IPv4len:], nl.rdxport[:2])
|
copy(addr[1+net.IPv4len:], nl.rdxport[:2])
|
||||||
return addr, nil
|
return addr, nil
|
||||||
|
52
proxy/redir/tcp_freebsd.go
Normal file
52
proxy/redir/tcp_freebsd.go
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
SO_ORIGINAL_DST = 80 // from linux/include/uapi/linux/netfilter_ipv4.h
|
||||||
|
IP6T_SO_ORIGINAL_DST = 80 // from linux/include/uapi/linux/netfilter_ipv6/ip6_tables.h
|
||||||
|
)
|
||||||
|
|
||||||
|
func parserPacket(conn net.Conn) (socks5.Addr, error) {
|
||||||
|
c, ok := conn.(*net.TCPConn)
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("only work with TCP connection")
|
||||||
|
}
|
||||||
|
|
||||||
|
rc, err := c.SyscallConn()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var addr socks5.Addr
|
||||||
|
|
||||||
|
rc.Control(func(fd uintptr) {
|
||||||
|
addr, err = getorigdst(fd)
|
||||||
|
})
|
||||||
|
|
||||||
|
return addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call getorigdst() from linux/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4.c
|
||||||
|
func getorigdst(fd uintptr) (socks5.Addr, error) {
|
||||||
|
raw := syscall.RawSockaddrInet4{}
|
||||||
|
siz := unsafe.Sizeof(raw)
|
||||||
|
_, _, err := syscall.Syscall6(syscall.SYS_GETSOCKOPT, fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST, uintptr(unsafe.Pointer(&raw)), uintptr(unsafe.Pointer(&siz)), 0)
|
||||||
|
if err != 0 {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := make([]byte, 1+net.IPv4len+2)
|
||||||
|
addr[0] = socks5.AtypIPv4
|
||||||
|
copy(addr[1:1+net.IPv4len], raw.Addr[:])
|
||||||
|
port := (*[2]byte)(unsafe.Pointer(&raw.Port)) // big-endian
|
||||||
|
addr[1+net.IPv4len], addr[1+net.IPv4len+1] = port[0], port[1]
|
||||||
|
return addr, nil
|
||||||
|
}
|
@ -6,7 +6,7 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -14,7 +14,7 @@ const (
|
|||||||
IP6T_SO_ORIGINAL_DST = 80 // from linux/include/uapi/linux/netfilter_ipv6/ip6_tables.h
|
IP6T_SO_ORIGINAL_DST = 80 // from linux/include/uapi/linux/netfilter_ipv6/ip6_tables.h
|
||||||
)
|
)
|
||||||
|
|
||||||
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
func parserPacket(conn net.Conn) (socks5.Addr, error) {
|
||||||
c, ok := conn.(*net.TCPConn)
|
c, ok := conn.(*net.TCPConn)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("only work with TCP connection")
|
return nil, errors.New("only work with TCP connection")
|
||||||
@ -25,7 +25,7 @@ func parserPacket(conn net.Conn) (socks.Addr, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var addr socks.Addr
|
var addr socks5.Addr
|
||||||
|
|
||||||
rc.Control(func(fd uintptr) {
|
rc.Control(func(fd uintptr) {
|
||||||
addr, err = getorigdst(fd)
|
addr, err = getorigdst(fd)
|
||||||
@ -35,7 +35,7 @@ func parserPacket(conn net.Conn) (socks.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Call getorigdst() from linux/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4.c
|
// Call getorigdst() from linux/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4.c
|
||||||
func getorigdst(fd uintptr) (socks.Addr, error) {
|
func getorigdst(fd uintptr) (socks5.Addr, error) {
|
||||||
raw := syscall.RawSockaddrInet4{}
|
raw := syscall.RawSockaddrInet4{}
|
||||||
siz := unsafe.Sizeof(raw)
|
siz := unsafe.Sizeof(raw)
|
||||||
if err := socketcall(GETSOCKOPT, fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST, uintptr(unsafe.Pointer(&raw)), uintptr(unsafe.Pointer(&siz)), 0); err != nil {
|
if err := socketcall(GETSOCKOPT, fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST, uintptr(unsafe.Pointer(&raw)), uintptr(unsafe.Pointer(&siz)), 0); err != nil {
|
||||||
@ -43,7 +43,7 @@ func getorigdst(fd uintptr) (socks.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr := make([]byte, 1+net.IPv4len+2)
|
addr := make([]byte, 1+net.IPv4len+2)
|
||||||
addr[0] = socks.AtypIPv4
|
addr[0] = socks5.AtypIPv4
|
||||||
copy(addr[1:1+net.IPv4len], raw.Addr[:])
|
copy(addr[1:1+net.IPv4len], raw.Addr[:])
|
||||||
port := (*[2]byte)(unsafe.Pointer(&raw.Port)) // big-endian
|
port := (*[2]byte)(unsafe.Pointer(&raw.Port)) // big-endian
|
||||||
addr[1+net.IPv4len], addr[1+net.IPv4len+1] = port[0], port[1]
|
addr[1+net.IPv4len], addr[1+net.IPv4len+1] = port[0], port[1]
|
||||||
|
@ -4,9 +4,9 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
func parserPacket(conn net.Conn) (socks5.Addr, error) {
|
||||||
return nil, errors.New("Windows not support yet")
|
return nil, errors.New("Windows not support yet")
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,16 @@
|
|||||||
package socks
|
package socks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/inbound"
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
authStore "github.com/Dreamacro/clash/proxy/auth"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -55,11 +57,16 @@ func (l *SockListener) Address() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func handleSocks(conn net.Conn) {
|
func handleSocks(conn net.Conn) {
|
||||||
target, err := socks.Handshake(conn)
|
target, command, err := socks5.ServerHandshake(conn, authStore.Authenticator())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
conn.Close()
|
conn.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||||
tun.Add(adapters.NewSocket(target, conn, C.SOCKS))
|
if command == socks5.CmdUDPAssociate {
|
||||||
|
defer conn.Close()
|
||||||
|
io.Copy(ioutil.Discard, conn)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.TCP))
|
||||||
}
|
}
|
||||||
|
@ -1 +1,68 @@
|
|||||||
package socks
|
package socks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SockUDPListener struct {
|
||||||
|
net.PacketConn
|
||||||
|
address string
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSocksUDPProxy(addr string) (*SockUDPListener, error) {
|
||||||
|
l, err := net.ListenPacket("udp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
sl := &SockUDPListener{l, addr, false}
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
buf := pool.BufPool.Get().([]byte)
|
||||||
|
n, remoteAddr, err := l.ReadFrom(buf)
|
||||||
|
if err != nil {
|
||||||
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
|
if sl.closed {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
handleSocksUDP(l, buf[:n], remoteAddr)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return sl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *SockUDPListener) Close() error {
|
||||||
|
l.closed = true
|
||||||
|
return l.PacketConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *SockUDPListener) Address() string {
|
||||||
|
return l.address
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleSocksUDP(pc net.PacketConn, buf []byte, addr net.Addr) {
|
||||||
|
target, payload, err := socks5.DecodeUDPPacket(buf)
|
||||||
|
if err != nil {
|
||||||
|
// Unresolved UDP packet, return buffer to the pool
|
||||||
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn := &fakeConn{
|
||||||
|
PacketConn: pc,
|
||||||
|
remoteAddr: addr,
|
||||||
|
targetAddr: target,
|
||||||
|
buffer: bytes.NewBuffer(payload),
|
||||||
|
bufRef: buf,
|
||||||
|
}
|
||||||
|
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.UDP))
|
||||||
|
}
|
||||||
|
39
proxy/socks/utils.go
Normal file
39
proxy/socks/utils.go
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package socks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
remoteAddr net.Addr
|
||||||
|
targetAddr socks5.Addr
|
||||||
|
buffer *bytes.Buffer
|
||||||
|
bufRef []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeConn) Read(b []byte) (n int, err error) {
|
||||||
|
return c.buffer.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeConn) Write(b []byte) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(c.targetAddr, b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return c.PacketConn.WriteTo(packet, c.remoteAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeConn) RemoteAddr() net.Addr {
|
||||||
|
return c.remoteAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeConn) Close() error {
|
||||||
|
err := c.PacketConn.Close()
|
||||||
|
pool.BufPool.Put(c.bufRef[:cap(c.bufRef)])
|
||||||
|
return err
|
||||||
|
}
|
@ -4,28 +4,28 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Final struct {
|
type Match struct {
|
||||||
adapter string
|
adapter string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Final) RuleType() C.RuleType {
|
func (f *Match) RuleType() C.RuleType {
|
||||||
return C.FINAL
|
return C.MATCH
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Final) IsMatch(metadata *C.Metadata) bool {
|
func (f *Match) IsMatch(metadata *C.Metadata) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Final) Adapter() string {
|
func (f *Match) Adapter() string {
|
||||||
return f.adapter
|
return f.adapter
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Final) Payload() string {
|
func (f *Match) Payload() string {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFinal(adapter string) *Final {
|
func NewMatch(adapter string) *Match {
|
||||||
return &Final{
|
return &Match{
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,10 +24,10 @@ func (g *GEOIP) RuleType() C.RuleType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (g *GEOIP) IsMatch(metadata *C.Metadata) bool {
|
func (g *GEOIP) IsMatch(metadata *C.Metadata) bool {
|
||||||
if metadata.IP == nil {
|
if metadata.DstIP == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
record, _ := mmdb.Country(*metadata.IP)
|
record, _ := mmdb.Country(*metadata.DstIP)
|
||||||
return record.Country.IsoCode == g.country
|
return record.Country.IsoCode == g.country
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,20 +7,24 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type IPCIDR struct {
|
type IPCIDR struct {
|
||||||
ipnet *net.IPNet
|
ipnet *net.IPNet
|
||||||
adapter string
|
adapter string
|
||||||
|
isSourceIP bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) RuleType() C.RuleType {
|
func (i *IPCIDR) RuleType() C.RuleType {
|
||||||
|
if i.isSourceIP {
|
||||||
|
return C.SrcIPCIDR
|
||||||
|
}
|
||||||
return C.IPCIDR
|
return C.IPCIDR
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) IsMatch(metadata *C.Metadata) bool {
|
func (i *IPCIDR) IsMatch(metadata *C.Metadata) bool {
|
||||||
if metadata.IP == nil {
|
ip := metadata.DstIP
|
||||||
return false
|
if i.isSourceIP {
|
||||||
|
ip = metadata.SrcIP
|
||||||
}
|
}
|
||||||
|
return ip != nil && i.ipnet.Contains(*ip)
|
||||||
return i.ipnet.Contains(*metadata.IP)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) Adapter() string {
|
func (i *IPCIDR) Adapter() string {
|
||||||
@ -31,12 +35,14 @@ func (i *IPCIDR) Payload() string {
|
|||||||
return i.ipnet.String()
|
return i.ipnet.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewIPCIDR(s string, adapter string) *IPCIDR {
|
func NewIPCIDR(s string, adapter string, isSourceIP bool) *IPCIDR {
|
||||||
_, ipnet, err := net.ParseCIDR(s)
|
_, ipnet, err := net.ParseCIDR(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
return &IPCIDR{
|
return &IPCIDR{
|
||||||
ipnet: ipnet,
|
ipnet: ipnet,
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
|
isSourceIP: isSourceIP,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
47
rules/port.go
Normal file
47
rules/port.go
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Port struct {
|
||||||
|
adapter string
|
||||||
|
port string
|
||||||
|
isSource bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Port) RuleType() C.RuleType {
|
||||||
|
if p.isSource {
|
||||||
|
return C.SrcPort
|
||||||
|
}
|
||||||
|
return C.DstPort
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Port) IsMatch(metadata *C.Metadata) bool {
|
||||||
|
if p.isSource {
|
||||||
|
return metadata.SrcPort == p.port
|
||||||
|
}
|
||||||
|
return metadata.DstPort == p.port
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Port) Adapter() string {
|
||||||
|
return p.adapter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Port) Payload() string {
|
||||||
|
return p.port
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPort(port string, adapter string, isSource bool) *Port {
|
||||||
|
_, err := strconv.Atoi(port)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &Port{
|
||||||
|
adapter: adapter,
|
||||||
|
port: port,
|
||||||
|
isSource: isSource,
|
||||||
|
}
|
||||||
|
}
|
@ -5,28 +5,24 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters/inbound"
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
||||||
// io.Copy default buffer size is 32 KiB
|
conn := newTrafficTrack(outbound, t.traffic)
|
||||||
// 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
|
|
||||||
)
|
|
||||||
|
|
||||||
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
|
|
||||||
|
|
||||||
func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter) {
|
|
||||||
conn := newTrafficTrack(proxy.Conn(), t.traffic)
|
|
||||||
req := request.R
|
req := request.R
|
||||||
host := req.Host
|
host := req.Host
|
||||||
|
|
||||||
|
inboundReeder := bufio.NewReader(request)
|
||||||
|
outboundReeder := bufio.NewReader(conn)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
keepAlive := strings.TrimSpace(strings.ToLower(req.Header.Get("Proxy-Connection"))) == "keep-alive"
|
||||||
|
|
||||||
req.Header.Set("Connection", "close")
|
req.Header.Set("Connection", "close")
|
||||||
req.RequestURI = ""
|
req.RequestURI = ""
|
||||||
adapters.RemoveHopByHopHeaders(req.Header)
|
adapters.RemoveHopByHopHeaders(req.Header)
|
||||||
@ -34,13 +30,23 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
br := bufio.NewReader(conn)
|
|
||||||
resp, err := http.ReadResponse(br, req)
|
handleResponse:
|
||||||
|
resp, err := http.ReadResponse(outboundReeder, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
adapters.RemoveHopByHopHeaders(resp.Header)
|
adapters.RemoveHopByHopHeaders(resp.Header)
|
||||||
if resp.ContentLength >= 0 {
|
|
||||||
|
if resp.StatusCode == http.StatusContinue {
|
||||||
|
err = resp.Write(request)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
goto handleResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
if keepAlive || resp.ContentLength >= 0 {
|
||||||
resp.Header.Set("Proxy-Connection", "keep-alive")
|
resp.Header.Set("Proxy-Connection", "keep-alive")
|
||||||
resp.Header.Set("Connection", "keep-alive")
|
resp.Header.Set("Connection", "keep-alive")
|
||||||
resp.Header.Set("Keep-Alive", "timeout=4")
|
resp.Header.Set("Keep-Alive", "timeout=4")
|
||||||
@ -48,12 +54,12 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter)
|
|||||||
} else {
|
} else {
|
||||||
resp.Close = true
|
resp.Close = true
|
||||||
}
|
}
|
||||||
err = resp.Write(request.Conn())
|
err = resp.Write(request)
|
||||||
if err != nil || resp.Close {
|
if err != nil || resp.Close {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err = http.ReadRequest(bufio.NewReader(request.Conn()))
|
req, err = http.ReadRequest(inboundReeder)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -66,9 +72,44 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) handleSOCKS(request *adapters.SocketAdapter, proxy C.ProxyAdapter) {
|
func (t *Tunnel) handleUDPToRemote(conn net.Conn, pc net.PacketConn, addr net.Addr) {
|
||||||
conn := newTrafficTrack(proxy.Conn(), t.traffic)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
relay(request.Conn(), conn)
|
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||||
|
|
||||||
|
n, err := conn.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err = pc.WriteTo(buf[:n], addr); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.traffic.Up() <- int64(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) handleUDPToLocal(conn net.Conn, pc net.PacketConn, key string, timeout time.Duration) {
|
||||||
|
buf := pool.BufPool.Get().([]byte)
|
||||||
|
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||||
|
defer t.natTable.Delete(key)
|
||||||
|
defer pc.Close()
|
||||||
|
|
||||||
|
for {
|
||||||
|
pc.SetReadDeadline(time.Now().Add(timeout))
|
||||||
|
n, _, err := pc.ReadFrom(buf)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err = conn.Write(buf[:n])
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.traffic.Down() <- int64(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) handleSocket(request *adapters.SocketAdapter, outbound net.Conn) {
|
||||||
|
conn := newTrafficTrack(outbound, t.traffic)
|
||||||
|
relay(request, conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
// relay copies between left and right bidirectionally.
|
// relay copies between left and right bidirectionally.
|
||||||
@ -76,16 +117,16 @@ func relay(leftConn, rightConn net.Conn) {
|
|||||||
ch := make(chan error)
|
ch := make(chan error)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
_, err := io.CopyBuffer(leftConn, rightConn, buf)
|
_, err := io.CopyBuffer(leftConn, rightConn, buf)
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
leftConn.SetReadDeadline(time.Now())
|
leftConn.SetReadDeadline(time.Now())
|
||||||
ch <- err
|
ch <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
buf := bufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
io.CopyBuffer(rightConn, leftConn, buf)
|
io.CopyBuffer(rightConn, leftConn, buf)
|
||||||
bufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
rightConn.SetReadDeadline(time.Now())
|
rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
<-ch
|
||||||
}
|
}
|
||||||
|
@ -60,6 +60,6 @@ func (m Mode) String() string {
|
|||||||
case Direct:
|
case Direct:
|
||||||
return "Direct"
|
return "Direct"
|
||||||
default:
|
default:
|
||||||
return "Unknow"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
263
tunnel/tunnel.go
263
tunnel/tunnel.go
@ -1,31 +1,40 @@
|
|||||||
package tunnel
|
package tunnel
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
InboundAdapter "github.com/Dreamacro/clash/adapters/inbound"
|
InboundAdapter "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
"github.com/Dreamacro/clash/component/nat"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/dns"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"gopkg.in/eapache/channels.v1"
|
channels "gopkg.in/eapache/channels.v1"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
tunnel *Tunnel
|
tunnel *Tunnel
|
||||||
once sync.Once
|
once sync.Once
|
||||||
|
|
||||||
|
// default timeout for UDP session
|
||||||
|
udpTimeout = 60 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
// Tunnel handle proxy socket and HTTP/SOCKS socket
|
// Tunnel handle relay inbound proxy and outbound proxy
|
||||||
type Tunnel struct {
|
type Tunnel struct {
|
||||||
queue *channels.InfiniteChannel
|
tcpQueue *channels.InfiniteChannel
|
||||||
rules []C.Rule
|
udpQueue *channels.InfiniteChannel
|
||||||
proxies map[string]C.Proxy
|
natTable *nat.Table
|
||||||
configLock *sync.RWMutex
|
rules []C.Rule
|
||||||
traffic *C.Traffic
|
proxies map[string]C.Proxy
|
||||||
resolver *dns.Resolver
|
configMux *sync.RWMutex
|
||||||
|
traffic *C.Traffic
|
||||||
|
|
||||||
|
// experimental features
|
||||||
|
ignoreResolveFail bool
|
||||||
|
|
||||||
// Outbound Rule
|
// Outbound Rule
|
||||||
mode Mode
|
mode Mode
|
||||||
@ -33,7 +42,12 @@ type Tunnel struct {
|
|||||||
|
|
||||||
// Add request to queue
|
// Add request to queue
|
||||||
func (t *Tunnel) Add(req C.ServerAdapter) {
|
func (t *Tunnel) Add(req C.ServerAdapter) {
|
||||||
t.queue.In() <- req
|
switch req.Metadata().NetWork {
|
||||||
|
case C.TCP:
|
||||||
|
t.tcpQueue.In() <- req
|
||||||
|
case C.UDP:
|
||||||
|
t.udpQueue.In() <- req
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Traffic return traffic of all connections
|
// Traffic return traffic of all connections
|
||||||
@ -48,9 +62,9 @@ func (t *Tunnel) Rules() []C.Rule {
|
|||||||
|
|
||||||
// UpdateRules handle update rules
|
// UpdateRules handle update rules
|
||||||
func (t *Tunnel) UpdateRules(rules []C.Rule) {
|
func (t *Tunnel) UpdateRules(rules []C.Rule) {
|
||||||
t.configLock.Lock()
|
t.configMux.Lock()
|
||||||
t.rules = rules
|
t.rules = rules
|
||||||
t.configLock.Unlock()
|
t.configMux.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Proxies return all proxies
|
// Proxies return all proxies
|
||||||
@ -60,9 +74,16 @@ func (t *Tunnel) Proxies() map[string]C.Proxy {
|
|||||||
|
|
||||||
// UpdateProxies handle update proxies
|
// UpdateProxies handle update proxies
|
||||||
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy) {
|
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy) {
|
||||||
t.configLock.Lock()
|
t.configMux.Lock()
|
||||||
t.proxies = proxies
|
t.proxies = proxies
|
||||||
t.configLock.Unlock()
|
t.configMux.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateExperimental handle update experimental config
|
||||||
|
func (t *Tunnel) UpdateExperimental(ignoreResolveFail bool) {
|
||||||
|
t.configMux.Lock()
|
||||||
|
t.ignoreResolveFail = ignoreResolveFail
|
||||||
|
t.configMux.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mode return current mode
|
// Mode return current mode
|
||||||
@ -75,56 +96,45 @@ func (t *Tunnel) SetMode(mode Mode) {
|
|||||||
t.mode = mode
|
t.mode = mode
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetResolver change the resolver of tunnel
|
|
||||||
func (t *Tunnel) SetResolver(resolver *dns.Resolver) {
|
|
||||||
t.resolver = resolver
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Tunnel) process() {
|
func (t *Tunnel) process() {
|
||||||
queue := t.queue.Out()
|
go func() {
|
||||||
for {
|
queue := t.udpQueue.Out()
|
||||||
elm := <-queue
|
for elm := range queue {
|
||||||
|
conn := elm.(C.ServerAdapter)
|
||||||
|
t.handleUDPConn(conn)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
queue := t.tcpQueue.Out()
|
||||||
|
for elm := range queue {
|
||||||
conn := elm.(C.ServerAdapter)
|
conn := elm.(C.ServerAdapter)
|
||||||
go t.handleConn(conn)
|
go t.handleTCPConn(conn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) resolveIP(host string) (net.IP, error) {
|
func (t *Tunnel) resolveIP(host string) (net.IP, error) {
|
||||||
if t.resolver == nil {
|
return dns.ResolveIP(host)
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipAddr.IP, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return t.resolver.ResolveIP(host)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
func (t *Tunnel) needLookupIP(metadata *C.Metadata) bool {
|
||||||
defer localConn.Close()
|
return dns.DefaultResolver != nil && (dns.DefaultResolver.IsMapping() || dns.DefaultResolver.IsFakeIP()) && metadata.Host == "" && metadata.DstIP != nil
|
||||||
metadata := localConn.Metadata()
|
}
|
||||||
|
|
||||||
if metadata.Source == C.REDIR && t.resolver != nil {
|
func (t *Tunnel) resolveMetadata(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
||||||
host, exist := t.resolver.IPToHost(*metadata.IP)
|
// preprocess enhanced-mode metadata
|
||||||
|
if t.needLookupIP(metadata) {
|
||||||
|
host, exist := dns.DefaultResolver.IPToHost(*metadata.DstIP)
|
||||||
if exist {
|
if exist {
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
metadata.AddrType = C.AtypDomainName
|
metadata.AddrType = C.AtypDomainName
|
||||||
|
if dns.DefaultResolver.IsFakeIP() {
|
||||||
|
metadata.DstIP = nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if metadata.IP == nil && metadata.AddrType == C.AtypDomainName {
|
|
||||||
ip, err := t.resolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
log.Debugln("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
|
||||||
} else {
|
|
||||||
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
|
|
||||||
metadata.IP = &ip
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.Debugln("[DNS] unknown%#v", metadata)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var proxy C.Proxy
|
var proxy C.Proxy
|
||||||
|
var rule C.Rule
|
||||||
switch t.mode {
|
switch t.mode {
|
||||||
case Direct:
|
case Direct:
|
||||||
proxy = t.proxies["DIRECT"]
|
proxy = t.proxies["DIRECT"]
|
||||||
@ -132,48 +142,167 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
|||||||
proxy = t.proxies["GLOBAL"]
|
proxy = t.proxies["GLOBAL"]
|
||||||
// Rule
|
// Rule
|
||||||
default:
|
default:
|
||||||
proxy = t.match(metadata)
|
var err error
|
||||||
|
proxy, rule, err = t.match(metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
remoConn, err := proxy.Generator(metadata)
|
return proxy, rule, nil
|
||||||
if err != nil {
|
}
|
||||||
log.Warnln("Proxy[%s] connect [%s] error: %s", proxy.Name(), metadata.String(), err.Error())
|
|
||||||
|
func (t *Tunnel) handleUDPConn(localConn C.ServerAdapter) {
|
||||||
|
metadata := localConn.Metadata()
|
||||||
|
if !metadata.Valid() {
|
||||||
|
log.Warnln("[Metadata] not valid: %#v", metadata)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer remoConn.Close()
|
|
||||||
|
src := localConn.RemoteAddr().String()
|
||||||
|
dst := metadata.RemoteAddress()
|
||||||
|
key := src + "-" + dst
|
||||||
|
|
||||||
|
pc, addr := t.natTable.Get(key)
|
||||||
|
if pc != nil {
|
||||||
|
t.handleUDPToRemote(localConn, pc, addr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
lockKey := key + "-lock"
|
||||||
|
wg, loaded := t.natTable.GetOrCreateLock(lockKey)
|
||||||
|
go func() {
|
||||||
|
if !loaded {
|
||||||
|
wg.Add(1)
|
||||||
|
proxy, rule, err := t.resolveMetadata(metadata)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("Parse metadata failed: %s", err.Error())
|
||||||
|
t.natTable.Delete(lockKey)
|
||||||
|
wg.Done()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawPc, nAddr, err := proxy.DialUDP(metadata)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("dial %s error: %s", proxy.Name(), err.Error())
|
||||||
|
t.natTable.Delete(lockKey)
|
||||||
|
wg.Done()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pc = rawPc
|
||||||
|
addr = nAddr
|
||||||
|
|
||||||
|
if rule != nil {
|
||||||
|
log.Infoln("%s --> %v match %s using %s", metadata.SrcIP.String(), metadata.String(), rule.RuleType().String(), rawPc.Chains().String())
|
||||||
|
} else {
|
||||||
|
log.Infoln("%s --> %v doesn't match any rule using DIRECT", metadata.SrcIP.String(), metadata.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
t.natTable.Set(key, pc, addr)
|
||||||
|
t.natTable.Delete(lockKey)
|
||||||
|
wg.Done()
|
||||||
|
go t.handleUDPToLocal(localConn, pc, key, udpTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
pc, addr := t.natTable.Get(key)
|
||||||
|
if pc != nil {
|
||||||
|
t.handleUDPToRemote(localConn, pc, addr)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) handleTCPConn(localConn C.ServerAdapter) {
|
||||||
|
defer localConn.Close()
|
||||||
|
|
||||||
|
metadata := localConn.Metadata()
|
||||||
|
if !metadata.Valid() {
|
||||||
|
log.Warnln("[Metadata] not valid: %#v", metadata)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy, rule, err := t.resolveMetadata(metadata)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("Parse metadata failed: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
remoteConn, err := proxy.Dial(metadata)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("dial %s error: %s", proxy.Name(), err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer remoteConn.Close()
|
||||||
|
|
||||||
|
if rule != nil {
|
||||||
|
log.Infoln("%s --> %v match %s using %s", metadata.SrcIP.String(), metadata.String(), rule.RuleType().String(), remoteConn.Chains().String())
|
||||||
|
} else {
|
||||||
|
log.Infoln("%s --> %v doesn't match any rule using DIRECT", metadata.SrcIP.String(), metadata.String())
|
||||||
|
}
|
||||||
|
|
||||||
switch adapter := localConn.(type) {
|
switch adapter := localConn.(type) {
|
||||||
case *InboundAdapter.HTTPAdapter:
|
case *InboundAdapter.HTTPAdapter:
|
||||||
t.handleHTTP(adapter, remoConn)
|
t.handleHTTP(adapter, remoteConn)
|
||||||
case *InboundAdapter.SocketAdapter:
|
case *InboundAdapter.SocketAdapter:
|
||||||
t.handleSOCKS(adapter, remoConn)
|
t.handleSocket(adapter, remoteConn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) match(metadata *C.Metadata) C.Proxy {
|
func (t *Tunnel) shouldResolveIP(rule C.Rule, metadata *C.Metadata) bool {
|
||||||
t.configLock.RLock()
|
return (rule.RuleType() == C.GEOIP || rule.RuleType() == C.IPCIDR) && metadata.Host != "" && metadata.DstIP == nil
|
||||||
defer t.configLock.RUnlock()
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
||||||
|
t.configMux.RLock()
|
||||||
|
defer t.configMux.RUnlock()
|
||||||
|
|
||||||
|
var resolved bool
|
||||||
|
|
||||||
|
if node := dns.DefaultHosts.Search(metadata.Host); node != nil {
|
||||||
|
ip := node.Data.(net.IP)
|
||||||
|
metadata.DstIP = &ip
|
||||||
|
resolved = true
|
||||||
|
}
|
||||||
|
|
||||||
for _, rule := range t.rules {
|
for _, rule := range t.rules {
|
||||||
|
if !resolved && t.shouldResolveIP(rule, metadata) {
|
||||||
|
ip, err := t.resolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
if !t.ignoreResolveFail {
|
||||||
|
return nil, nil, fmt.Errorf("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
||||||
|
}
|
||||||
|
log.Debugln("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
||||||
|
} else {
|
||||||
|
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
|
||||||
|
metadata.DstIP = &ip
|
||||||
|
}
|
||||||
|
resolved = true
|
||||||
|
}
|
||||||
|
|
||||||
if rule.IsMatch(metadata) {
|
if rule.IsMatch(metadata) {
|
||||||
a, ok := t.proxies[rule.Adapter()]
|
adapter, ok := t.proxies[rule.Adapter()]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
log.Infoln("%v match %s using %s", metadata.String(), rule.RuleType().String(), rule.Adapter())
|
|
||||||
return a
|
if metadata.NetWork == C.UDP && !adapter.SupportUDP() {
|
||||||
|
log.Debugln("%v UDP is not supported", adapter.Name())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return adapter, rule, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Infoln("%v doesn't match any rule using DIRECT", metadata.String())
|
return t.proxies["DIRECT"], nil, nil
|
||||||
return t.proxies["DIRECT"]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newTunnel() *Tunnel {
|
func newTunnel() *Tunnel {
|
||||||
return &Tunnel{
|
return &Tunnel{
|
||||||
queue: channels.NewInfiniteChannel(),
|
tcpQueue: channels.NewInfiniteChannel(),
|
||||||
proxies: make(map[string]C.Proxy),
|
udpQueue: channels.NewInfiniteChannel(),
|
||||||
configLock: &sync.RWMutex{},
|
natTable: nat.New(),
|
||||||
traffic: C.NewTraffic(time.Second),
|
proxies: make(map[string]C.Proxy),
|
||||||
mode: Rule,
|
configMux: &sync.RWMutex{},
|
||||||
|
traffic: C.NewTraffic(time.Second),
|
||||||
|
mode: Rule,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user