Compare commits
116 Commits
Author | SHA1 | Date | |
---|---|---|---|
fcb1a7813a | |||
6f1bc3d65b | |||
2b93c9d4c9 | |||
f93d6aa294 | |||
f192d591c7 | |||
03c249ecb1 | |||
da5db36ccf | |||
ca6e67a384 | |||
6636db242b | |||
f5715c4f42 | |||
9cfd26d440 | |||
dc24dd4d89 | |||
a64cea5011 | |||
f6743d4d21 | |||
970643b144 | |||
05bf4d44ab | |||
c7a349e1fe | |||
01a477bd3d | |||
91e35f2f6a | |||
b0e062dc7c | |||
09cd34ec07 | |||
da391356dd | |||
502aa61c0e | |||
cc6d496143 | |||
10e0231bc1 | |||
fd63707399 | |||
c5757a9b11 | |||
370bc769d5 | |||
ce7cb138d4 | |||
d2174149c1 | |||
bcba14e05e | |||
19cbe52456 | |||
e12d46f619 | |||
990bba4a05 | |||
03c563a58e | |||
f943f9284d | |||
1f556d4ae5 | |||
082d3bbf04 | |||
4895bcefca | |||
1235c9a939 | |||
82343c70e9 | |||
94d1972782 | |||
ce07eda428 | |||
0fd2f8e5ee | |||
e863c66ad9 | |||
b68af43389 | |||
381f764507 | |||
64e3791654 | |||
40a94be208 | |||
a0f077b091 | |||
7b80377849 | |||
8fff0968bf | |||
ea9cd41197 | |||
5c7fa6b18b | |||
16c9445459 | |||
04e05c6a85 | |||
85a67988b9 | |||
2fd59cb31c | |||
220e4f0608 | |||
3e68faecb2 | |||
eb778ad6e2 | |||
0caa8e05a3 | |||
1d0d5667fd | |||
0724d4ea52 | |||
5d34cba681 | |||
4082a2c700 | |||
fcb46e7706 | |||
834baa9e27 | |||
af13acc171 | |||
f2dbabeaa0 | |||
f4c51cdb0e | |||
a5f2bd3152 | |||
613a0c36dd | |||
8ec025b56a | |||
2a2e61652f | |||
ad25a89dd2 | |||
26618901d4 | |||
ebe1cee6dc | |||
fc4f119049 | |||
2b87b907ae | |||
35e572406b | |||
228d674d93 | |||
752944d381 | |||
63308472ad | |||
0208e32933 | |||
410b272b50 | |||
ea424a7694 | |||
36f4ceafa1 | |||
674f4be24d | |||
63c967b2b3 | |||
a1a58c31ae | |||
295d649624 | |||
7347c28f75 | |||
8389150318 | |||
7357d2d0c2 | |||
d540a0d29f | |||
d55e1b664b | |||
88c7ccf749 | |||
3cacfb8a7f | |||
0eef9bbf5d | |||
39b45513af | |||
283e4e1f4f | |||
bd0a1ae1a7 | |||
018a6ba041 | |||
9c2ace1f91 | |||
17224a32cb | |||
05ab653103 | |||
c2c8f82f96 | |||
330a3391e3 | |||
79e5338113 | |||
bc4ca2818b | |||
46b8e2eec1 | |||
cd9f496fc9 | |||
ef301af04f | |||
6ffbb7c89e | |||
961250f998 |
15
.travis.yml
15
.travis.yml
@ -1,22 +1,17 @@
|
|||||||
language: go
|
language: go
|
||||||
sudo: false
|
sudo: false
|
||||||
go:
|
go:
|
||||||
- "1.10"
|
- "1.11"
|
||||||
before_install:
|
|
||||||
- go get -u github.com/golang/dep/cmd/dep
|
|
||||||
install:
|
install:
|
||||||
- "$GOPATH/bin/dep ensure"
|
- "go mod download"
|
||||||
env:
|
env:
|
||||||
global:
|
global:
|
||||||
- NAME=clash
|
- NAME=clash
|
||||||
- BINDIR=bin
|
- BINDIR=bin
|
||||||
|
- GO111MODULE=on
|
||||||
script:
|
script:
|
||||||
- go test
|
- go test ./...
|
||||||
- GOARCH=amd64 GOOS=linux go build -o $BINDIR/$NAME-linux
|
before_deploy: make -j releases
|
||||||
- GOARCH=amd64 GOOS=darwin go build -o $BINDIR/$NAME-macos
|
|
||||||
- chmod +x $BINDIR/$NAME-*
|
|
||||||
- gzip $BINDIR/$NAME-linux
|
|
||||||
- gzip $BINDIR/$NAME-macos
|
|
||||||
deploy:
|
deploy:
|
||||||
provider: releases
|
provider: releases
|
||||||
prerelease: true
|
prerelease: true
|
||||||
|
23
Dockerfile
Normal file
23
Dockerfile
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
FROM golang:latest as builder
|
||||||
|
|
||||||
|
RUN wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz -O /tmp/GeoLite2-Country.tar.gz && \
|
||||||
|
tar zxvf /tmp/GeoLite2-Country.tar.gz -C /tmp && \
|
||||||
|
mv /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /Country.mmdb
|
||||||
|
|
||||||
|
WORKDIR /clash-src
|
||||||
|
|
||||||
|
COPY . /clash-src
|
||||||
|
|
||||||
|
RUN go mod download && \
|
||||||
|
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '-w -s' -o /clash
|
||||||
|
|
||||||
|
FROM alpine:latest
|
||||||
|
|
||||||
|
RUN apk add --no-cache ca-certificates
|
||||||
|
|
||||||
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
|
COPY --from=builder /clash /
|
||||||
|
|
||||||
|
EXPOSE 7890 7891
|
||||||
|
|
||||||
|
ENTRYPOINT ["/clash"]
|
84
Gopkg.lock
generated
84
Gopkg.lock
generated
@ -1,84 +0,0 @@
|
|||||||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
|
||||||
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
name = "github.com/Yawning/chacha20"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "e3b1f968fc6397b51d963fee8ec8711a47bc0ce8"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "github.com/eapache/queue"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "44cc805cf13205b55f69e14bcb69867d1ae92f98"
|
|
||||||
version = "v1.1.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "github.com/oschwald/geoip2-golang"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "7118115686e16b77967cdbf55d1b944fe14ad312"
|
|
||||||
version = "v1.2.1"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "github.com/oschwald/maxminddb-golang"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "c5bec84d1963260297932a1b7a1753c8420717a7"
|
|
||||||
version = "v1.3.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "github.com/riobard/go-shadowsocks2"
|
|
||||||
packages = [
|
|
||||||
"core",
|
|
||||||
"shadowaead",
|
|
||||||
"shadowstream",
|
|
||||||
"socks"
|
|
||||||
]
|
|
||||||
revision = "8346403248229fc7e10d7a259de8e9352a9d8830"
|
|
||||||
version = "v0.1.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "github.com/sirupsen/logrus"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "c155da19408a8799da419ed3eeb0cb5db0ad5dbc"
|
|
||||||
version = "v1.0.5"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
name = "golang.org/x/crypto"
|
|
||||||
packages = [
|
|
||||||
"chacha20poly1305",
|
|
||||||
"hkdf",
|
|
||||||
"internal/chacha20",
|
|
||||||
"poly1305",
|
|
||||||
"ssh/terminal"
|
|
||||||
]
|
|
||||||
revision = "8ac0e0d97ce45cd83d1d7243c060cb8461dda5e9"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
name = "golang.org/x/sys"
|
|
||||||
packages = [
|
|
||||||
"cpu",
|
|
||||||
"unix",
|
|
||||||
"windows"
|
|
||||||
]
|
|
||||||
revision = "9527bec2660bd847c050fda93a0f0c6dee0800bb"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "gopkg.in/eapache/channels.v1"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "47238d5aae8c0fefd518ef2bee46290909cf8263"
|
|
||||||
version = "v1.1.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
name = "gopkg.in/ini.v1"
|
|
||||||
packages = ["."]
|
|
||||||
revision = "06f5f3d67269ccec1fe5fe4134ba6e982984f7f5"
|
|
||||||
version = "v1.37.0"
|
|
||||||
|
|
||||||
[solve-meta]
|
|
||||||
analyzer-name = "dep"
|
|
||||||
analyzer-version = 1
|
|
||||||
inputs-digest = "4297c505508c6cdd8c94fd4ef29bc6940c65fea81e125fcf871a316b6e671a71"
|
|
||||||
solver-name = "gps-cdcl"
|
|
||||||
solver-version = 1
|
|
50
Gopkg.toml
50
Gopkg.toml
@ -1,50 +0,0 @@
|
|||||||
# Gopkg.toml example
|
|
||||||
#
|
|
||||||
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
|
|
||||||
# for detailed Gopkg.toml documentation.
|
|
||||||
#
|
|
||||||
# required = ["github.com/user/thing/cmd/thing"]
|
|
||||||
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
|
|
||||||
#
|
|
||||||
# [[constraint]]
|
|
||||||
# name = "github.com/user/project"
|
|
||||||
# version = "1.0.0"
|
|
||||||
#
|
|
||||||
# [[constraint]]
|
|
||||||
# name = "github.com/user/project2"
|
|
||||||
# branch = "dev"
|
|
||||||
# source = "github.com/myfork/project2"
|
|
||||||
#
|
|
||||||
# [[override]]
|
|
||||||
# name = "github.com/x/y"
|
|
||||||
# version = "2.4.0"
|
|
||||||
#
|
|
||||||
# [prune]
|
|
||||||
# non-go = false
|
|
||||||
# go-tests = true
|
|
||||||
# unused-packages = true
|
|
||||||
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/oschwald/geoip2-golang"
|
|
||||||
version = "1.2.1"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/riobard/go-shadowsocks2"
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/sirupsen/logrus"
|
|
||||||
version = "1.0.5"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "gopkg.in/eapache/channels.v1"
|
|
||||||
version = "1.1.0"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "gopkg.in/ini.v1"
|
|
||||||
version = "1.37.0"
|
|
||||||
|
|
||||||
[prune]
|
|
||||||
go-tests = true
|
|
||||||
unused-packages = true
|
|
23
Makefile
Normal file
23
Makefile
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
NAME=clash
|
||||||
|
BINDIR=bin
|
||||||
|
GOBUILD=CGO_ENABLED=0 go build -ldflags '-w -s'
|
||||||
|
|
||||||
|
all: linux macos win64
|
||||||
|
|
||||||
|
linux:
|
||||||
|
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
macos:
|
||||||
|
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
win64:
|
||||||
|
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
releases: linux macos win64
|
||||||
|
chmod +x $(BINDIR)/$(NAME)-*
|
||||||
|
gzip $(BINDIR)/$(NAME)-linux
|
||||||
|
gzip $(BINDIR)/$(NAME)-macos
|
||||||
|
zip -m -j $(BINDIR)/$(NAME)-win64.zip $(BINDIR)/$(NAME)-win64.exe
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm $(BINDIR)/*
|
168
README.md
168
README.md
@ -1,12 +1,32 @@
|
|||||||
# Clash
|
<h1 align="center">
|
||||||
|
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
||||||
|
<br>
|
||||||
|
Clash
|
||||||
|
<br>
|
||||||
|
</h1>
|
||||||
|
|
||||||
A rule based proxy in Go.
|
<h4 align="center">A rule based tunnel in Go.</h4>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://travis-ci.org/Dreamacro/clash">
|
||||||
|
<img src="https://img.shields.io/travis/Dreamacro/clash.svg?style=flat-square"
|
||||||
|
alt="Travis-CI">
|
||||||
|
</a>
|
||||||
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
|
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/Dreamacro/clash/releases">
|
||||||
|
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- HTTP/HTTPS and SOCKS proxy
|
- HTTP/HTTPS and SOCKS protocol
|
||||||
- Surge like configuration
|
- Surge like configuration
|
||||||
- GeoIP rule support
|
- GeoIP rule support
|
||||||
|
- Support Vmess/Shadowsocks/Socks5
|
||||||
|
- Support for Netfilter TCP redirect
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@ -18,7 +38,7 @@ 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: [release](https://github.com/Dreamacro/clash/releases)
|
||||||
|
|
||||||
Requires Go >= 1.10.
|
Requires Go >= 1.11.
|
||||||
|
|
||||||
## Daemon
|
## Daemon
|
||||||
|
|
||||||
@ -26,37 +46,145 @@ Unfortunately, there is no native elegant way to implement golang's daemon.
|
|||||||
|
|
||||||
So we can use third-party daemon tools like pm2, supervisor, and so on.
|
So we can use third-party daemon tools like pm2, supervisor, and so on.
|
||||||
|
|
||||||
In the case of 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`.
|
||||||
|
|
||||||
|
[Run clash in docker](https://github.com/Dreamacro/clash/wiki/Run-clash-in-docker)
|
||||||
|
|
||||||
## Config
|
## Config
|
||||||
|
|
||||||
Configuration file at `$HOME/.config/clash/config.ini`
|
**NOTE: after v0.8.0, clash using yaml as configuration file**
|
||||||
|
|
||||||
|
The default configuration directory is `$HOME/.config/clash`
|
||||||
|
|
||||||
|
The name of the configuration file is `config.yml`
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
```sh
|
||||||
|
clash -d .
|
||||||
|
```
|
||||||
|
|
||||||
Below is a simple demo configuration file:
|
Below is a simple demo configuration file:
|
||||||
|
|
||||||
```ini
|
```yml
|
||||||
[General]
|
# port of HTTP
|
||||||
port = 7890
|
port: 7890
|
||||||
socks-port = 7891
|
|
||||||
|
|
||||||
[Proxy]
|
# port of SOCKS5
|
||||||
# name = ss, server, port, cipher, password
|
socks-port: 7891
|
||||||
|
|
||||||
|
# redir port for Linux and macOS
|
||||||
|
# redir-port: 7892
|
||||||
|
|
||||||
|
allow-lan: false
|
||||||
|
|
||||||
|
# Rule / Global/ Direct (default is Rule)
|
||||||
|
mode: Rule
|
||||||
|
|
||||||
|
# set log level to stdout (default is info)
|
||||||
|
# info / warning / error / debug / silent
|
||||||
|
log-level: info
|
||||||
|
|
||||||
|
# A RESTful API for clash
|
||||||
|
external-controller: 127.0.0.1:9090
|
||||||
|
|
||||||
|
# Secret for RESTful API (Optional)
|
||||||
|
# secret: ""
|
||||||
|
|
||||||
|
dns:
|
||||||
|
# enable: true # set true to enable dns (default is false)
|
||||||
|
# ipv6: false # default is false
|
||||||
|
# listen: 0.0.0.0:53
|
||||||
|
# enhanced-mode: redir-host
|
||||||
|
# nameserver:
|
||||||
|
# - 114.114.114.114
|
||||||
|
# - tls://dns.rubyfish.cn:853 # dns over tls
|
||||||
|
# fallback: # concurrent request with nameserver, fallback used when GEOIP country isn't CN
|
||||||
|
# - 8.8.8.8
|
||||||
|
|
||||||
|
Proxy:
|
||||||
|
|
||||||
|
# shadowsocks
|
||||||
# The types of cipher are consistent with go-shadowsocks2
|
# The types of cipher are consistent with go-shadowsocks2
|
||||||
# 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
|
# 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
|
||||||
Proxy = ss, server, port, AEAD_CHACHA20_POLY1305, password
|
# In addition to what go-shadowsocks2 supports, it also supports chacha20 rc4-md5 xchacha20-ietf-poly1305
|
||||||
|
- { name: "ss1", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password" }
|
||||||
|
- { name: "ss2", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password", obfs: tls, obfs-host: bing.com }
|
||||||
|
|
||||||
[Rule]
|
# vmess
|
||||||
DOMAIN-SUFFIX,google.com,Proxy
|
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
||||||
DOMAIN-KEYWORD,google,Proxy
|
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto }
|
||||||
DOMAIN-SUFFIX,ad.com,REJECT
|
# with tls
|
||||||
GEOIP,CN,DIRECT
|
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true }
|
||||||
FINAL,,Proxy # note: there is two ","
|
# with tls and skip-cert-verify
|
||||||
|
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true, skip-cert-verify: true }
|
||||||
|
# with ws
|
||||||
|
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path }
|
||||||
|
# with ws + tls
|
||||||
|
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path, tls: true }
|
||||||
|
|
||||||
|
# socks5
|
||||||
|
- { name: "socks", type: socks5, server: server, port: 443 }
|
||||||
|
# socks5 with authentication
|
||||||
|
- { name: "socks", type: socks5, server: server, port: 443, username: "username", password: "password" }
|
||||||
|
# with tls
|
||||||
|
- { name: "socks", type: socks5, server: server, port: 443, tls: true }
|
||||||
|
# with tls and skip-cert-verify
|
||||||
|
- { name: "socks", type: socks5, server: server, port: 443, tls: true, skip-cert-verify: true }
|
||||||
|
|
||||||
|
# http
|
||||||
|
- { name: "http", type: http, server: server, port: 443 }
|
||||||
|
# http with authentication
|
||||||
|
- { name: "http", type: http, server: server, port: 443, username: "username", password: "password" }
|
||||||
|
# with tls (https)
|
||||||
|
- { name: "http", type: http, server: server, port: 443, tls: true }
|
||||||
|
# with tls (https) and skip-cert-verify
|
||||||
|
- { name: "http", type: http, server: server, port: 443, tls: true, skip-cert-verify: true }
|
||||||
|
|
||||||
|
Proxy Group:
|
||||||
|
# url-test select which proxy will be used by benchmarking speed to a URL.
|
||||||
|
- { name: "auto", type: url-test, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
|
||||||
|
|
||||||
|
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
||||||
|
- { name: "fallback-auto", type: fallback, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
|
||||||
|
|
||||||
|
# select is used for selecting proxy or proxy group
|
||||||
|
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
||||||
|
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
|
||||||
|
|
||||||
|
Rule:
|
||||||
|
- DOMAIN-SUFFIX,google.com,Proxy
|
||||||
|
- DOMAIN-KEYWORD,google,Proxy
|
||||||
|
- DOMAIN,google.com,Proxy
|
||||||
|
- DOMAIN-SUFFIX,ad.com,REJECT
|
||||||
|
- IP-CIDR,127.0.0.0/8,DIRECT
|
||||||
|
- GEOIP,CN,DIRECT
|
||||||
|
# FINAL would remove after prerelease
|
||||||
|
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
||||||
|
- MATCH,Proxy
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Thanks
|
||||||
|
|
||||||
|
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
|
|
||||||
|
[v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
||||||
|
|
||||||
## TODO
|
## TODO
|
||||||
|
|
||||||
- [ ] Complementing the necessary rule operators
|
- [x] Complementing the necessary rule operators
|
||||||
|
- [x] Redir proxy
|
||||||
|
- [ ] UDP support
|
||||||
|
- [ ] Connection manager
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DirectAdapter is a directly connected adapter
|
|
||||||
type DirectAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReadWriter is used to handle network traffic
|
|
||||||
func (d *DirectAdapter) ReadWriter() io.ReadWriter {
|
|
||||||
return d.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (d *DirectAdapter) Close() {
|
|
||||||
d.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (d *DirectAdapter) Conn() net.Conn {
|
|
||||||
return d.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
type Direct struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Direct) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
|
||||||
c, err := net.Dial("tcp", net.JoinHostPort(addr.String(), addr.Port))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.(*net.TCPConn).SetKeepAlive(true)
|
|
||||||
return &DirectAdapter{conn: c}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
|
||||||
return &Direct{}
|
|
||||||
}
|
|
64
adapters/inbound/http.go
Normal file
64
adapters/inbound/http.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HTTPAdapter is a adapter for HTTP connection
|
||||||
|
type HTTPAdapter struct {
|
||||||
|
metadata *C.Metadata
|
||||||
|
conn net.Conn
|
||||||
|
R *http.Request
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close HTTP connection
|
||||||
|
func (h *HTTPAdapter) Close() {
|
||||||
|
h.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata return destination metadata
|
||||||
|
func (h *HTTPAdapter) Metadata() *C.Metadata {
|
||||||
|
return h.metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn return raw net.Conn of HTTP
|
||||||
|
func (h *HTTPAdapter) Conn() net.Conn {
|
||||||
|
return h.conn
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHTTP is HTTPAdapter generator
|
||||||
|
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
||||||
|
return &HTTPAdapter{
|
||||||
|
metadata: parseHTTPAddr(request),
|
||||||
|
R: request,
|
||||||
|
conn: conn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveHopByHopHeaders remove hop-by-hop header
|
||||||
|
func RemoveHopByHopHeaders(header http.Header) {
|
||||||
|
// Strip hop-by-hop header based on RFC:
|
||||||
|
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
|
||||||
|
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
|
||||||
|
|
||||||
|
header.Del("Proxy-Connection")
|
||||||
|
header.Del("Proxy-Authenticate")
|
||||||
|
header.Del("Proxy-Authorization")
|
||||||
|
header.Del("TE")
|
||||||
|
header.Del("Trailers")
|
||||||
|
header.Del("Transfer-Encoding")
|
||||||
|
header.Del("Upgrade")
|
||||||
|
|
||||||
|
connections := header.Get("Connection")
|
||||||
|
header.Del("Connection")
|
||||||
|
if len(connections) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, h := range strings.Split(connections, ",") {
|
||||||
|
header.Del(strings.TrimSpace(h))
|
||||||
|
}
|
||||||
|
}
|
14
adapters/inbound/https.go
Normal file
14
adapters/inbound/https.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewHTTPS is HTTPAdapter generator
|
||||||
|
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
||||||
|
return &SocketAdapter{
|
||||||
|
metadata: parseHTTPAddr(request),
|
||||||
|
conn: conn,
|
||||||
|
}
|
||||||
|
}
|
40
adapters/inbound/socket.go
Normal file
40
adapters/inbound/socket.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SocketAdapter is a adapter for socks and redir connection
|
||||||
|
type SocketAdapter struct {
|
||||||
|
conn net.Conn
|
||||||
|
metadata *C.Metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close socks and redir connection
|
||||||
|
func (s *SocketAdapter) Close() {
|
||||||
|
s.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata return destination metadata
|
||||||
|
func (s *SocketAdapter) Metadata() *C.Metadata {
|
||||||
|
return s.metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn return raw net.Conn
|
||||||
|
func (s *SocketAdapter) Conn() net.Conn {
|
||||||
|
return s.conn
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSocket is SocketAdapter generator
|
||||||
|
func NewSocket(target socks.Addr, conn net.Conn, source C.SourceType) *SocketAdapter {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.Source = source
|
||||||
|
|
||||||
|
return &SocketAdapter{
|
||||||
|
conn: conn,
|
||||||
|
metadata: metadata,
|
||||||
|
}
|
||||||
|
}
|
63
adapters/inbound/util.go
Normal file
63
adapters/inbound/util.go
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseSocksAddr(target socks.Addr) *C.Metadata {
|
||||||
|
metadata := &C.Metadata{
|
||||||
|
NetWork: C.TCP,
|
||||||
|
AddrType: int(target[0]),
|
||||||
|
}
|
||||||
|
|
||||||
|
switch target[0] {
|
||||||
|
case socks.AtypDomainName:
|
||||||
|
metadata.Host = string(target[2 : 2+target[1]])
|
||||||
|
metadata.Port = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
|
case socks.AtypIPv4:
|
||||||
|
ip := net.IP(target[1 : 1+net.IPv4len])
|
||||||
|
metadata.IP = &ip
|
||||||
|
metadata.Port = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
|
case socks.AtypIPv6:
|
||||||
|
ip := net.IP(target[1 : 1+net.IPv6len])
|
||||||
|
metadata.IP = &ip
|
||||||
|
metadata.Port = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||||
|
host := request.URL.Hostname()
|
||||||
|
port := request.URL.Port()
|
||||||
|
if port == "" {
|
||||||
|
port = "80"
|
||||||
|
}
|
||||||
|
|
||||||
|
metadata := &C.Metadata{
|
||||||
|
NetWork: C.TCP,
|
||||||
|
Source: C.HTTP,
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: host,
|
||||||
|
IP: nil,
|
||||||
|
Port: port,
|
||||||
|
}
|
||||||
|
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
if ip != nil {
|
||||||
|
switch {
|
||||||
|
case ip.To4() == nil:
|
||||||
|
metadata.AddrType = C.AtypIPv6
|
||||||
|
default:
|
||||||
|
metadata.AddrType = C.AtypIPv4
|
||||||
|
}
|
||||||
|
metadata.IP = &ip
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
}
|
57
adapters/outbound/direct.go
Normal file
57
adapters/outbound/direct.go
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DirectAdapter is a directly connected adapter
|
||||||
|
type DirectAdapter struct {
|
||||||
|
conn net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close is used to close connection
|
||||||
|
func (d *DirectAdapter) Close() {
|
||||||
|
d.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
return &DirectAdapter{conn: c}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Direct) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": d.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDirect() *Direct {
|
||||||
|
return &Direct{}
|
||||||
|
}
|
149
adapters/outbound/fallback.go
Normal file
149
adapters/outbound/fallback.go
Normal file
@ -0,0 +1,149 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type proxy struct {
|
||||||
|
RawProxy C.Proxy
|
||||||
|
Valid bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Fallback struct {
|
||||||
|
name string
|
||||||
|
proxies []*proxy
|
||||||
|
rawURL string
|
||||||
|
interval time.Duration
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FallbackOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Proxies []string `proxy:"proxies"`
|
||||||
|
URL string `proxy:"url"`
|
||||||
|
Interval int `proxy:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Name() string {
|
||||||
|
return f.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Type() C.AdapterType {
|
||||||
|
return C.Fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Now() string {
|
||||||
|
_, proxy := f.findNextValidProxy(0)
|
||||||
|
if proxy != nil {
|
||||||
|
return proxy.RawProxy.Name()
|
||||||
|
}
|
||||||
|
return f.proxies[0].RawProxy.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||||
|
idx := 0
|
||||||
|
var proxy *proxy
|
||||||
|
for {
|
||||||
|
idx, proxy = f.findNextValidProxy(idx)
|
||||||
|
if proxy == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
adapter, err = proxy.RawProxy.Generator(metadata)
|
||||||
|
if err != nil {
|
||||||
|
proxy.Valid = false
|
||||||
|
idx++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return f.proxies[0].RawProxy.Generator(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range f.proxies {
|
||||||
|
all = append(all, proxy.RawProxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": f.Type().String(),
|
||||||
|
"now": f.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Close() {
|
||||||
|
f.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) loop() {
|
||||||
|
tick := time.NewTicker(f.interval)
|
||||||
|
go f.validTest()
|
||||||
|
Loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-tick.C:
|
||||||
|
go f.validTest()
|
||||||
|
case <-f.done:
|
||||||
|
break Loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) findNextValidProxy(start int) (int, *proxy) {
|
||||||
|
for i := start; i < len(f.proxies); i++ {
|
||||||
|
if f.proxies[i].Valid {
|
||||||
|
return i, f.proxies[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) validTest() {
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(len(f.proxies))
|
||||||
|
|
||||||
|
for _, p := range f.proxies {
|
||||||
|
go func(p *proxy) {
|
||||||
|
_, err := DelayTest(p.RawProxy, f.rawURL)
|
||||||
|
p.Valid = err == nil
|
||||||
|
wg.Done()
|
||||||
|
}(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
||||||
|
_, err := urlToMetadata(option.URL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) < 1 {
|
||||||
|
return nil, errors.New("The number of proxies cannot be 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := time.Duration(option.Interval) * time.Second
|
||||||
|
warpperProxies := make([]*proxy, len(proxies))
|
||||||
|
for idx := range proxies {
|
||||||
|
warpperProxies[idx] = &proxy{
|
||||||
|
RawProxy: proxies[idx],
|
||||||
|
Valid: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Fallback := &Fallback{
|
||||||
|
name: option.Name,
|
||||||
|
proxies: warpperProxies,
|
||||||
|
rawURL: option.URL,
|
||||||
|
interval: interval,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
go Fallback.loop()
|
||||||
|
return Fallback, nil
|
||||||
|
}
|
148
adapters/outbound/http.go
Normal file
148
adapters/outbound/http.go
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
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 {
|
||||||
|
addr string
|
||||||
|
name string
|
||||||
|
user string
|
||||||
|
pass string
|
||||||
|
tls bool
|
||||||
|
skipCertVerify bool
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type HttpOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Http) Name() string {
|
||||||
|
return h.name
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
|
err = cc.Handshake()
|
||||||
|
c = cc
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error", h.addr)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
if err := h.shakeHand(metadata, c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &HTTPAdapter{conn: c}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
var err error
|
||||||
|
|
||||||
|
buf.WriteString("CONNECT ")
|
||||||
|
buf.WriteString(net.JoinHostPort(metadata.Host, metadata.Port))
|
||||||
|
buf.WriteString(" HTTP/1.1\r\n")
|
||||||
|
buf.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
||||||
|
|
||||||
|
if h.user != "" && h.pass != "" {
|
||||||
|
auth := h.user + ":" + h.pass
|
||||||
|
buf.WriteString("Proxy-Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) + "\r\n")
|
||||||
|
}
|
||||||
|
// header ended
|
||||||
|
buf.WriteString("\r\n")
|
||||||
|
|
||||||
|
_, err = rw.Write(buf.Bytes())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var req http.Request
|
||||||
|
resp, err := http.ReadResponse(bufio.NewReader(rw), &req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == 200 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == 407 {
|
||||||
|
return errors.New("HTTP need auth")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode == 405 {
|
||||||
|
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) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": h.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHttp(option HttpOption) *Http {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ClientSessionCache: getClientSessionCache(),
|
||||||
|
MinVersion: tls.VersionTLS11,
|
||||||
|
MaxVersion: tls.VersionTLS12,
|
||||||
|
ServerName: option.Server,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Http{
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
name: option.Name,
|
||||||
|
user: option.UserName,
|
||||||
|
pass: option.Password,
|
||||||
|
tls: option.TLS,
|
||||||
|
skipCertVerify: option.SkipCertVerify,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
76
adapters/outbound/reject.go
Normal file
76
adapters/outbound/reject.go
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
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 {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reject) Name() string {
|
||||||
|
return "REJECT"
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
return &Reject{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type NopConn struct{}
|
||||||
|
|
||||||
|
func (rw *NopConn) Read(b []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *NopConn) Write(b []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close is fake function for net.Conn
|
||||||
|
func (rw *NopConn) Close() error { return nil }
|
||||||
|
|
||||||
|
// LocalAddr is fake function for net.Conn
|
||||||
|
func (rw *NopConn) LocalAddr() net.Addr { return nil }
|
||||||
|
|
||||||
|
// RemoteAddr is fake function for net.Conn
|
||||||
|
func (rw *NopConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
|
||||||
|
// SetDeadline is fake function for net.Conn
|
||||||
|
func (rw *NopConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
// SetReadDeadline is fake function for net.Conn
|
||||||
|
func (rw *NopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
// SetWriteDeadline is fake function for net.Conn
|
||||||
|
func (rw *NopConn) SetWriteDeadline(time.Time) error { return nil }
|
76
adapters/outbound/selector.go
Normal file
76
adapters/outbound/selector.go
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Selector struct {
|
||||||
|
name string
|
||||||
|
selected C.Proxy
|
||||||
|
proxies map[string]C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
type SelectorOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Proxies []string `proxy:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Name() string {
|
||||||
|
return s.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Type() C.AdapterType {
|
||||||
|
return C.Selector
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||||
|
return s.selected.Generator(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for k := range s.proxies {
|
||||||
|
all = append(all, k)
|
||||||
|
}
|
||||||
|
sort.Strings(all)
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": s.Type().String(),
|
||||||
|
"now": s.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Now() string {
|
||||||
|
return s.selected.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Set(name string) error {
|
||||||
|
proxy, exist := s.proxies[name]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("Proxy does not exist")
|
||||||
|
}
|
||||||
|
s.selected = proxy
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("Provide at least one proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping := make(map[string]C.Proxy)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
mapping[proxy.Name()] = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Selector{
|
||||||
|
name: name,
|
||||||
|
proxies: mapping,
|
||||||
|
selected: proxies[0],
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
123
adapters/outbound/shadowsocks.go
Normal file
123
adapters/outbound/shadowsocks.go
Normal file
@ -0,0 +1,123 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/simple-obfs"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"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 {
|
||||||
|
server string
|
||||||
|
name string
|
||||||
|
obfs string
|
||||||
|
obfsHost string
|
||||||
|
cipher core.Cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShadowSocksOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
|
ObfsHost string `proxy:"obfs-host,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) Name() string {
|
||||||
|
return ss.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) Type() C.AdapterType {
|
||||||
|
return C.Shadowsocks
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||||
|
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error", ss.server)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
switch ss.obfs {
|
||||||
|
case "tls":
|
||||||
|
c = obfs.NewTLSObfs(c, ss.obfsHost)
|
||||||
|
case "http":
|
||||||
|
_, port, _ := net.SplitHostPort(ss.server)
|
||||||
|
c = obfs.NewHTTPObfs(c, ss.obfsHost, port)
|
||||||
|
}
|
||||||
|
c = ss.cipher.StreamConn(c)
|
||||||
|
_, err = c.Write(serializesSocksAddr(metadata))
|
||||||
|
return &ShadowsocksAdapter{conn: c}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": ss.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
|
server := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
cipher := option.Cipher
|
||||||
|
password := option.Password
|
||||||
|
ciph, err := core.PickCipher(cipher, nil, password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
obfs := option.Obfs
|
||||||
|
obfsHost := "bing.com"
|
||||||
|
if option.ObfsHost != "" {
|
||||||
|
obfsHost = option.ObfsHost
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ShadowSocks{
|
||||||
|
server: server,
|
||||||
|
name: option.Name,
|
||||||
|
cipher: ciph,
|
||||||
|
obfs: obfs,
|
||||||
|
obfsHost: obfsHost,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
|
var buf [][]byte
|
||||||
|
aType := uint8(metadata.AddrType)
|
||||||
|
p, _ := strconv.Atoi(metadata.Port)
|
||||||
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case socks.AtypDomainName:
|
||||||
|
len := uint8(len(metadata.Host))
|
||||||
|
host := []byte(metadata.Host)
|
||||||
|
buf = [][]byte{{aType, len}, host, port}
|
||||||
|
case socks.AtypIPv4:
|
||||||
|
host := metadata.IP.To4()
|
||||||
|
buf = [][]byte{{aType}, host, port}
|
||||||
|
case socks.AtypIPv6:
|
||||||
|
host := metadata.IP.To16()
|
||||||
|
buf = [][]byte{{aType}, host, port}
|
||||||
|
}
|
||||||
|
return bytes.Join(buf, nil)
|
||||||
|
}
|
165
adapters/outbound/socks5.go
Normal file
165
adapters/outbound/socks5.go
Normal file
@ -0,0 +1,165 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
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 {
|
||||||
|
addr string
|
||||||
|
name string
|
||||||
|
user string
|
||||||
|
pass string
|
||||||
|
tls bool
|
||||||
|
skipCertVerify bool
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type Socks5Option struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *Socks5) Name() string {
|
||||||
|
return ss.name
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
|
err = cc.Handshake()
|
||||||
|
c = cc
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error", ss.addr)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
if err := ss.shakeHand(metadata, c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Socks5Adapter{conn: c}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *Socks5) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]string{
|
||||||
|
"type": ss.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// VER, METHOD
|
||||||
|
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[0] != 5 {
|
||||||
|
return errors.New("SOCKS version error")
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ClientSessionCache: getClientSessionCache(),
|
||||||
|
MinVersion: tls.VersionTLS11,
|
||||||
|
MaxVersion: tls.VersionTLS12,
|
||||||
|
ServerName: option.Server,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Socks5{
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
name: option.Name,
|
||||||
|
user: option.UserName,
|
||||||
|
pass: option.Password,
|
||||||
|
tls: option.TLS,
|
||||||
|
skipCertVerify: option.SkipCertVerify,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
141
adapters/outbound/urltest.go
Normal file
141
adapters/outbound/urltest.go
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type URLTest struct {
|
||||||
|
name string
|
||||||
|
proxies []C.Proxy
|
||||||
|
rawURL string
|
||||||
|
fast C.Proxy
|
||||||
|
interval time.Duration
|
||||||
|
done chan struct{}
|
||||||
|
once int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type URLTestOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Proxies []string `proxy:"proxies"`
|
||||||
|
URL string `proxy:"url"`
|
||||||
|
Interval int `proxy:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Name() string {
|
||||||
|
return u.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Type() C.AdapterType {
|
||||||
|
return C.URLTest
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Now() string {
|
||||||
|
return u.fast.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||||
|
a, err := u.fast.Generator(metadata)
|
||||||
|
if err != nil {
|
||||||
|
go u.speedTest()
|
||||||
|
}
|
||||||
|
return a, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range u.proxies {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
sort.Strings(all)
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": u.Type().String(),
|
||||||
|
"now": u.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Close() {
|
||||||
|
u.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) loop() {
|
||||||
|
tick := time.NewTicker(u.interval)
|
||||||
|
go u.speedTest()
|
||||||
|
Loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-tick.C:
|
||||||
|
go u.speedTest()
|
||||||
|
case <-u.done:
|
||||||
|
break Loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) speedTest() {
|
||||||
|
if atomic.AddInt32(&u.once, 1) != 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer atomic.StoreInt32(&u.once, 0)
|
||||||
|
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(len(u.proxies))
|
||||||
|
c := make(chan interface{})
|
||||||
|
fast := selectFast(c)
|
||||||
|
timer := time.NewTimer(u.interval)
|
||||||
|
|
||||||
|
for _, p := range u.proxies {
|
||||||
|
go func(p C.Proxy) {
|
||||||
|
_, err := DelayTest(p, u.rawURL)
|
||||||
|
if err == nil {
|
||||||
|
c <- p
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
wg.Wait()
|
||||||
|
close(c)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-timer.C:
|
||||||
|
// Wait for fast to return or close.
|
||||||
|
<-fast
|
||||||
|
case p, open := <-fast:
|
||||||
|
if open {
|
||||||
|
u.fast = p.(C.Proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
||||||
|
_, err := urlToMetadata(option.URL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(proxies) < 1 {
|
||||||
|
return nil, errors.New("The number of proxies cannot be 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := time.Duration(option.Interval) * time.Second
|
||||||
|
urlTest := &URLTest{
|
||||||
|
name: option.Name,
|
||||||
|
proxies: proxies[:],
|
||||||
|
rawURL: option.URL,
|
||||||
|
fast: proxies[0],
|
||||||
|
interval: interval,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
once: 0,
|
||||||
|
}
|
||||||
|
go urlTest.loop()
|
||||||
|
return urlTest, nil
|
||||||
|
}
|
111
adapters/outbound/util.go
Normal file
111
adapters/outbound/util.go
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
tcpTimeout = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalClientSessionCache tls.ClientSessionCache
|
||||||
|
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) {
|
||||||
|
u, err := url.Parse(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
port := u.Port()
|
||||||
|
if port == "" {
|
||||||
|
if u.Scheme == "https" {
|
||||||
|
port = "443"
|
||||||
|
} else if u.Scheme == "http" {
|
||||||
|
port = "80"
|
||||||
|
} else {
|
||||||
|
err = fmt.Errorf("%s scheme not Support", rawURL)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = C.Metadata{
|
||||||
|
AddrType: C.AtypDomainName,
|
||||||
|
Host: u.Hostname(),
|
||||||
|
IP: nil,
|
||||||
|
Port: port,
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
tcp.SetKeepAlive(true)
|
||||||
|
tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getClientSessionCache() tls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return globalClientSessionCache
|
||||||
|
}
|
121
adapters/outbound/vmess.go
Normal file
121
adapters/outbound/vmess.go
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
package adapters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/vmess"
|
||||||
|
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 {
|
||||||
|
name string
|
||||||
|
server string
|
||||||
|
client *vmess.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type VmessOption struct {
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UUID string `proxy:"uuid"`
|
||||||
|
AlterID int `proxy:"alterId"`
|
||||||
|
Cipher string `proxy:"cipher"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
|
Network string `proxy:"network,omitempty"`
|
||||||
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vmess) Name() string {
|
||||||
|
return v.name
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
return nil, fmt.Errorf("%s connect error", v.server)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = v.client.New(c, parseVmessAddr(metadata))
|
||||||
|
return &VmessAdapter{conn: c}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vmess) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": v.Type().String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
|
security := strings.ToLower(option.Cipher)
|
||||||
|
client, err := vmess.NewClient(vmess.Config{
|
||||||
|
UUID: option.UUID,
|
||||||
|
AlterID: uint16(option.AlterID),
|
||||||
|
Security: security,
|
||||||
|
TLS: option.TLS,
|
||||||
|
HostName: option.Server,
|
||||||
|
Port: strconv.Itoa(option.Port),
|
||||||
|
NetWork: option.Network,
|
||||||
|
WebSocketPath: option.WSPath,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
SessionCacahe: getClientSessionCache(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Vmess{
|
||||||
|
name: option.Name,
|
||||||
|
server: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
client: client,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||||
|
var addrType byte
|
||||||
|
var addr []byte
|
||||||
|
switch metadata.AddrType {
|
||||||
|
case C.AtypIPv4:
|
||||||
|
addrType = byte(vmess.AtypIPv4)
|
||||||
|
addr = make([]byte, net.IPv4len)
|
||||||
|
copy(addr[:], metadata.IP.To4())
|
||||||
|
case C.AtypIPv6:
|
||||||
|
addrType = byte(vmess.AtypIPv6)
|
||||||
|
addr = make([]byte, net.IPv6len)
|
||||||
|
copy(addr[:], metadata.IP.To16())
|
||||||
|
case C.AtypDomainName:
|
||||||
|
addrType = byte(vmess.AtypDomainName)
|
||||||
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
|
addr[0] = byte(len(metadata.Host))
|
||||||
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.Atoi(metadata.Port)
|
||||||
|
return &vmess.DstAddr{
|
||||||
|
AddrType: addrType,
|
||||||
|
Addr: addr,
|
||||||
|
Port: uint(port),
|
||||||
|
}
|
||||||
|
}
|
@ -1,46 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RejectAdapter is a reject connected adapter
|
|
||||||
type RejectAdapter struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReadWriter is used to handle network traffic
|
|
||||||
func (r *RejectAdapter) ReadWriter() io.ReadWriter {
|
|
||||||
return &NopRW{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (r *RejectAdapter) Close() {}
|
|
||||||
|
|
||||||
// Close is used to close connection
|
|
||||||
func (r *RejectAdapter) Conn() net.Conn {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type Reject struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Reject) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
|
||||||
return &RejectAdapter{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewReject() *Reject {
|
|
||||||
return &Reject{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type NopRW struct{}
|
|
||||||
|
|
||||||
func (rw *NopRW) Read(b []byte) (int, error) {
|
|
||||||
return len(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw *NopRW) Write(b []byte) (int, error) {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
@ -1,96 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"github.com/riobard/go-shadowsocks2/core"
|
|
||||||
"github.com/riobard/go-shadowsocks2/socks"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ShadowsocksAdapter is a shadowsocks adapter
|
|
||||||
type ShadowsocksAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReadWriter is used to handle network traffic
|
|
||||||
func (ss *ShadowsocksAdapter) ReadWriter() io.ReadWriter {
|
|
||||||
return ss.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 {
|
|
||||||
server string
|
|
||||||
cipher string
|
|
||||||
password string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
|
||||||
var key []byte
|
|
||||||
ciph, _ := core.PickCipher(ss.cipher, key, ss.password)
|
|
||||||
c, err := net.Dial("tcp", ss.server)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error", ss.server)
|
|
||||||
}
|
|
||||||
c.(*net.TCPConn).SetKeepAlive(true)
|
|
||||||
c = ciph.StreamConn(c)
|
|
||||||
_, err = c.Write(serializesSocksAddr(addr))
|
|
||||||
return &ShadowsocksAdapter{conn: c}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewShadowSocks(ssURL string) *ShadowSocks {
|
|
||||||
server, cipher, password, _ := parseURL(ssURL)
|
|
||||||
return &ShadowSocks{
|
|
||||||
server: server,
|
|
||||||
cipher: cipher,
|
|
||||||
password: password,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseURL(s string) (addr, cipher, password string, err error) {
|
|
||||||
u, err := url.Parse(s)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addr = u.Host
|
|
||||||
if u.User != nil {
|
|
||||||
cipher = u.User.Username()
|
|
||||||
password, _ = u.User.Password()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func serializesSocksAddr(addr *C.Addr) []byte {
|
|
||||||
var buf [][]byte
|
|
||||||
aType := uint8(addr.AddrType)
|
|
||||||
p, _ := strconv.Atoi(addr.Port)
|
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
|
||||||
switch addr.AddrType {
|
|
||||||
case socks.AtypDomainName:
|
|
||||||
len := uint8(len(addr.Host))
|
|
||||||
host := []byte(addr.Host)
|
|
||||||
buf = [][]byte{[]byte{aType, len}, host, port}
|
|
||||||
case socks.AtypIPv4:
|
|
||||||
host := addr.IP.To4()
|
|
||||||
buf = [][]byte{[]byte{aType}, host, port}
|
|
||||||
case socks.AtypIPv6:
|
|
||||||
host := addr.IP.To16()
|
|
||||||
buf = [][]byte{[]byte{aType}, host, port}
|
|
||||||
}
|
|
||||||
return bytes.Join(buf, []byte(""))
|
|
||||||
}
|
|
91
common/cache/cache.go
vendored
Normal file
91
common/cache/cache.go
vendored
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cache store element with a expired time
|
||||||
|
type Cache struct {
|
||||||
|
*cache
|
||||||
|
}
|
||||||
|
|
||||||
|
type cache struct {
|
||||||
|
mapping sync.Map
|
||||||
|
janitor *janitor
|
||||||
|
}
|
||||||
|
|
||||||
|
type element struct {
|
||||||
|
Expired time.Time
|
||||||
|
Payload interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put element in Cache with its ttl
|
||||||
|
func (c *cache) Put(key interface{}, payload interface{}, ttl time.Duration) {
|
||||||
|
c.mapping.Store(key, &element{
|
||||||
|
Payload: payload,
|
||||||
|
Expired: time.Now().Add(ttl),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get element in Cache, and drop when it expired
|
||||||
|
func (c *cache) Get(key interface{}) interface{} {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
elm := item.(*element)
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return elm.Payload
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cache) cleanup() {
|
||||||
|
c.mapping.Range(func(k, v interface{}) bool {
|
||||||
|
key := k.(string)
|
||||||
|
elm := v.(*element)
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type janitor struct {
|
||||||
|
interval time.Duration
|
||||||
|
stop chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *janitor) process(c *cache) {
|
||||||
|
ticker := time.NewTicker(j.interval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
c.cleanup()
|
||||||
|
case <-j.stop:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopJanitor(c *Cache) {
|
||||||
|
c.janitor.stop <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return *Cache
|
||||||
|
func New(interval time.Duration) *Cache {
|
||||||
|
j := &janitor{
|
||||||
|
interval: interval,
|
||||||
|
stop: make(chan struct{}),
|
||||||
|
}
|
||||||
|
c := &cache{janitor: j}
|
||||||
|
go j.process(c)
|
||||||
|
C := &Cache{c}
|
||||||
|
runtime.SetFinalizer(C, stopJanitor)
|
||||||
|
return C
|
||||||
|
}
|
70
common/cache/cache_test.go
vendored
Normal file
70
common/cache/cache_test.go
vendored
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCache_Basic(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("string", "a", ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
if i.(int) != 1 {
|
||||||
|
t.Error("should recv 1")
|
||||||
|
}
|
||||||
|
|
||||||
|
s := c.Get("string")
|
||||||
|
if s.(string) != "a" {
|
||||||
|
t.Error("should recv 'a'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_TTL(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
if i.(int) != 1 {
|
||||||
|
t.Error("should recv 1")
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i = c.Get("int")
|
||||||
|
if i != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoCleanup(t *testing.T) {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i := c.Get("int")
|
||||||
|
if i != nil {
|
||||||
|
t.Error("should recv nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoGC(t *testing.T) {
|
||||||
|
sign := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New(interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
sign <- struct{}{}
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-sign
|
||||||
|
runtime.GC()
|
||||||
|
}
|
3
common/observable/iterable.go
Normal file
3
common/observable/iterable.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package observable
|
||||||
|
|
||||||
|
type Iterable <-chan interface{}
|
@ -50,7 +50,6 @@ func (o *Observable) Subscribe() (Subscription, error) {
|
|||||||
func (o *Observable) UnSubscribe(sub Subscription) {
|
func (o *Observable) UnSubscribe(sub Subscription) {
|
||||||
elm, exist := o.listener.Load(sub)
|
elm, exist := o.listener.Load(sub)
|
||||||
if !exist {
|
if !exist {
|
||||||
println("not exist")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
subscriber := elm.(*Subscriber)
|
subscriber := elm.(*Subscriber)
|
@ -27,11 +27,7 @@ func TestObservable(t *testing.T) {
|
|||||||
t.Error(err)
|
t.Error(err)
|
||||||
}
|
}
|
||||||
count := 0
|
count := 0
|
||||||
for {
|
for range data {
|
||||||
_, open := <-data
|
|
||||||
if !open {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
count = count + 1
|
count = count + 1
|
||||||
}
|
}
|
||||||
if count != 5 {
|
if count != 5 {
|
||||||
@ -49,11 +45,7 @@ func TestObservable_MutilSubscribe(t *testing.T) {
|
|||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan interface{}) {
|
||||||
for {
|
for range ch {
|
||||||
_, open := <-ch
|
|
||||||
if !open {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
count = count + 1
|
count = count + 1
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
@ -80,6 +72,25 @@ func TestObservable_UnSubscribe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
||||||
|
iter := iterator([]interface{}{1})
|
||||||
|
src := NewObservable(iter)
|
||||||
|
data, _ := src.Subscribe()
|
||||||
|
<-data
|
||||||
|
|
||||||
|
_, closed := src.Subscribe()
|
||||||
|
if closed == nil {
|
||||||
|
t.Error("Observable should be closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
||||||
|
sub := Subscription(make(chan interface{}))
|
||||||
|
iter := iterator([]interface{}{1})
|
||||||
|
src := NewObservable(iter)
|
||||||
|
src.UnSubscribe(sub)
|
||||||
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
||||||
// waiting for other goroutine recycle
|
// waiting for other goroutine recycle
|
||||||
time.Sleep(120 * time.Millisecond)
|
time.Sleep(120 * time.Millisecond)
|
||||||
@ -97,11 +108,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(max)
|
wg.Add(max)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan interface{}) {
|
||||||
for {
|
for range ch {
|
||||||
_, open := <-ch
|
|
||||||
if !open {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
22
common/picker/picker.go
Normal file
22
common/picker/picker.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package picker
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
func SelectFast(ctx context.Context, in <-chan interface{}) <-chan interface{} {
|
||||||
|
out := make(chan interface{})
|
||||||
|
go func() {
|
||||||
|
select {
|
||||||
|
case p, open := <-in:
|
||||||
|
if open {
|
||||||
|
out <- p
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
|
||||||
|
close(out)
|
||||||
|
for range in {
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
44
common/picker/picker_test.go
Normal file
44
common/picker/picker_test.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package picker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sleepAndSend(delay int, in chan<- interface{}, input interface{}) {
|
||||||
|
time.Sleep(time.Millisecond * time.Duration(delay))
|
||||||
|
in <- input
|
||||||
|
}
|
||||||
|
|
||||||
|
func sleepAndClose(delay int, in chan interface{}) {
|
||||||
|
time.Sleep(time.Millisecond * time.Duration(delay))
|
||||||
|
close(in)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPicker_Basic(t *testing.T) {
|
||||||
|
in := make(chan interface{})
|
||||||
|
fast := SelectFast(context.Background(), in)
|
||||||
|
go sleepAndSend(20, in, 1)
|
||||||
|
go sleepAndSend(30, in, 2)
|
||||||
|
go sleepAndClose(40, in)
|
||||||
|
|
||||||
|
number, exist := <-fast
|
||||||
|
if !exist || number != 1 {
|
||||||
|
t.Error("should recv 1", exist, number)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPicker_Timeout(t *testing.T) {
|
||||||
|
in := make(chan interface{})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
|
||||||
|
defer cancel()
|
||||||
|
fast := SelectFast(ctx, in)
|
||||||
|
go sleepAndSend(20, in, 1)
|
||||||
|
go sleepAndClose(30, in)
|
||||||
|
|
||||||
|
_, exist := <-fast
|
||||||
|
if exist {
|
||||||
|
t.Error("should recv false")
|
||||||
|
}
|
||||||
|
}
|
160
common/structure/structure.go
Normal file
160
common/structure/structure.go
Normal file
@ -0,0 +1,160 @@
|
|||||||
|
package structure
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Option is the configuration that is used to create a new decoder
|
||||||
|
type Option struct {
|
||||||
|
TagName string
|
||||||
|
WeaklyTypedInput bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decoder is the core of structure
|
||||||
|
type Decoder struct {
|
||||||
|
option *Option
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDecoder return a Decoder by Option
|
||||||
|
func NewDecoder(option Option) *Decoder {
|
||||||
|
if option.TagName == "" {
|
||||||
|
option.TagName = "structure"
|
||||||
|
}
|
||||||
|
return &Decoder{option: &option}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode transform a map[string]interface{} to a struct
|
||||||
|
func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
||||||
|
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||||
|
return fmt.Errorf("Decode must recive a ptr struct")
|
||||||
|
}
|
||||||
|
t := reflect.TypeOf(dst).Elem()
|
||||||
|
v := reflect.ValueOf(dst).Elem()
|
||||||
|
for idx := 0; idx < v.NumField(); idx++ {
|
||||||
|
field := t.Field(idx)
|
||||||
|
|
||||||
|
tag := field.Tag.Get(d.option.TagName)
|
||||||
|
str := strings.SplitN(tag, ",", 2)
|
||||||
|
key := str[0]
|
||||||
|
omitempty := false
|
||||||
|
if len(str) > 1 {
|
||||||
|
omitempty = str[1] == "omitempty"
|
||||||
|
}
|
||||||
|
|
||||||
|
value, ok := src[key]
|
||||||
|
if !ok {
|
||||||
|
if omitempty {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("key %s missing", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := d.decode(key, value, v.Field(idx))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
|
||||||
|
switch val.Kind() {
|
||||||
|
case reflect.Int:
|
||||||
|
return d.decodeInt(name, data, val)
|
||||||
|
case reflect.String:
|
||||||
|
return d.decodeString(name, data, val)
|
||||||
|
case reflect.Bool:
|
||||||
|
return d.decodeBool(name, data, val)
|
||||||
|
case reflect.Slice:
|
||||||
|
return d.decodeSlice(name, data, val)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("type %s not support", val.Kind().String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (err error) {
|
||||||
|
dataVal := reflect.ValueOf(data)
|
||||||
|
kind := dataVal.Kind()
|
||||||
|
switch {
|
||||||
|
case kind == reflect.Int:
|
||||||
|
val.SetInt(dataVal.Int())
|
||||||
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
|
var i int64
|
||||||
|
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
|
||||||
|
if err == nil {
|
||||||
|
val.SetInt(i)
|
||||||
|
} else {
|
||||||
|
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf(
|
||||||
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
|
name, val.Type(), dataVal.Type(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) (err error) {
|
||||||
|
dataVal := reflect.ValueOf(data)
|
||||||
|
kind := dataVal.Kind()
|
||||||
|
switch {
|
||||||
|
case kind == reflect.String:
|
||||||
|
val.SetString(dataVal.String())
|
||||||
|
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
||||||
|
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf(
|
||||||
|
"'%s' expected type'%s', got unconvertible type '%s'",
|
||||||
|
name, val.Type(), dataVal.Type(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (err error) {
|
||||||
|
dataVal := reflect.ValueOf(data)
|
||||||
|
kind := dataVal.Kind()
|
||||||
|
switch {
|
||||||
|
case kind == reflect.Bool:
|
||||||
|
val.SetBool(dataVal.Bool())
|
||||||
|
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
||||||
|
val.SetBool(dataVal.Int() != 0)
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf(
|
||||||
|
"'%s' expected type'%s', got unconvertible type '%s'",
|
||||||
|
name, val.Type(), dataVal.Type(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
|
||||||
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
valType := val.Type()
|
||||||
|
valElemType := valType.Elem()
|
||||||
|
|
||||||
|
if dataVal.Kind() != reflect.Slice {
|
||||||
|
return fmt.Errorf("'%s' is not a slice", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
valSlice := val
|
||||||
|
for i := 0; i < dataVal.Len(); i++ {
|
||||||
|
currentData := dataVal.Index(i).Interface()
|
||||||
|
for valSlice.Len() <= i {
|
||||||
|
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
||||||
|
}
|
||||||
|
currentField := valSlice.Index(i)
|
||||||
|
|
||||||
|
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
||||||
|
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val.Set(valSlice)
|
||||||
|
return nil
|
||||||
|
}
|
141
common/structure/structure_test.go
Normal file
141
common/structure/structure_test.go
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
package structure
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var decoder = NewDecoder(Option{TagName: "test"})
|
||||||
|
var weakTypeDecoder = NewDecoder(Option{TagName: "test", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
type Baz struct {
|
||||||
|
Foo int `test:"foo"`
|
||||||
|
Bar string `test:"bar"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type BazSlice struct {
|
||||||
|
Foo int `test:"foo"`
|
||||||
|
Bar []string `test:"bar"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type BazOptional struct {
|
||||||
|
Foo int `test:"foo,omitempty"`
|
||||||
|
Bar string `test:"bar,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_Basic(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": "test",
|
||||||
|
"extra": false,
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &Baz{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: "test",
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Baz{}
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(s, goal) {
|
||||||
|
t.Fatalf("bad: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_Slice(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": []string{"one", "two"},
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazSlice{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: []string{"one", "two"},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(s, goal) {
|
||||||
|
t.Fatalf("bad: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_Optional(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{
|
||||||
|
"foo": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazOptional{
|
||||||
|
Foo: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazOptional{}
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(s, goal) {
|
||||||
|
t.Fatalf("bad: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_MissingKey(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{
|
||||||
|
"foo": 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Baz{}
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("should throw error: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_ParamError(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{}
|
||||||
|
s := Baz{}
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("should throw error: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceTypeError(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": []int{1, 2},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("should throw error: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_WeakType(t *testing.T) {
|
||||||
|
rawMap := map[string]interface{}{
|
||||||
|
"foo": "1",
|
||||||
|
"bar": []int{1},
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazSlice{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: []string{"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := weakTypeDecoder.Decode(rawMap, s)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(s, goal) {
|
||||||
|
t.Fatalf("bad: %#v", s)
|
||||||
|
}
|
||||||
|
}
|
88
component/simple-obfs/http.go
Normal file
88
component/simple-obfs/http.go
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
package obfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HTTPObfs is shadowsocks http simple-obfs implementation
|
||||||
|
type HTTPObfs struct {
|
||||||
|
net.Conn
|
||||||
|
host string
|
||||||
|
port string
|
||||||
|
buf []byte
|
||||||
|
offset int
|
||||||
|
firstRequest bool
|
||||||
|
firstResponse bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ho *HTTPObfs) Read(b []byte) (int, error) {
|
||||||
|
if ho.buf != nil {
|
||||||
|
n := copy(b, ho.buf[ho.offset:])
|
||||||
|
ho.offset += n
|
||||||
|
if ho.offset == len(ho.buf) {
|
||||||
|
ho.buf = nil
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if ho.firstResponse {
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
n, err := ho.Conn.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
idx := bytes.Index(buf[:n], []byte("\r\n\r\n"))
|
||||||
|
if idx == -1 {
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
ho.firstResponse = false
|
||||||
|
length := n - (idx + 4)
|
||||||
|
n = copy(b, buf[idx+4:n])
|
||||||
|
if length > n {
|
||||||
|
ho.buf = buf[:idx+4+length]
|
||||||
|
ho.offset = idx + 4 + n
|
||||||
|
} else {
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
return ho.Conn.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ho *HTTPObfs) Write(b []byte) (int, error) {
|
||||||
|
if ho.firstRequest {
|
||||||
|
randBytes := make([]byte, 16)
|
||||||
|
rand.Read(randBytes)
|
||||||
|
req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s/", ho.host), bytes.NewBuffer(b[:]))
|
||||||
|
req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", rand.Int()%54, rand.Int()%2))
|
||||||
|
req.Header.Set("Upgrade", "websocket")
|
||||||
|
req.Header.Set("Connection", "Upgrade")
|
||||||
|
req.Host = fmt.Sprintf("%s:%s", ho.host, ho.port)
|
||||||
|
req.Header.Set("Sec-WebSocket-Key", base64.URLEncoding.EncodeToString(randBytes))
|
||||||
|
req.ContentLength = int64(len(b))
|
||||||
|
err := req.Write(ho.Conn)
|
||||||
|
ho.firstRequest = false
|
||||||
|
return len(b), err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ho.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHTTPObfs return a HTTPObfs
|
||||||
|
func NewHTTPObfs(conn net.Conn, host string, port string) net.Conn {
|
||||||
|
return &HTTPObfs{
|
||||||
|
Conn: conn,
|
||||||
|
firstRequest: true,
|
||||||
|
firstResponse: true,
|
||||||
|
host: host,
|
||||||
|
port: port,
|
||||||
|
}
|
||||||
|
}
|
203
component/simple-obfs/tls.go
Normal file
203
component/simple-obfs/tls.go
Normal file
@ -0,0 +1,203 @@
|
|||||||
|
package obfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rand.Seed(time.Now().Unix())
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
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
|
||||||
|
type TLSObfs struct {
|
||||||
|
net.Conn
|
||||||
|
server string
|
||||||
|
remain int
|
||||||
|
firstRequest bool
|
||||||
|
firstResponse bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (to *TLSObfs) read(b []byte, discardN int) (int, error) {
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
_, err := io.ReadFull(to.Conn, buf[:discardN])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
|
||||||
|
sizeBuf := make([]byte, 2)
|
||||||
|
_, err = io.ReadFull(to.Conn, sizeBuf)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
length := int(binary.BigEndian.Uint16(sizeBuf))
|
||||||
|
if length > len(b) {
|
||||||
|
n, err := to.Conn.Read(b)
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
to.remain = length - n
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return io.ReadFull(to.Conn, b[:length])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (to *TLSObfs) Read(b []byte) (int, error) {
|
||||||
|
if to.remain > 0 {
|
||||||
|
length := to.remain
|
||||||
|
if length > len(b) {
|
||||||
|
length = len(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := io.ReadFull(to.Conn, b[:length])
|
||||||
|
to.remain -= n
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if to.firstResponse {
|
||||||
|
// type + ver + lensize + 91 = 96
|
||||||
|
// type + ver + lensize + 1 = 6
|
||||||
|
// type + ver = 3
|
||||||
|
to.firstResponse = false
|
||||||
|
return to.read(b, 105)
|
||||||
|
}
|
||||||
|
|
||||||
|
// type + ver = 3
|
||||||
|
return to.read(b, 3)
|
||||||
|
}
|
||||||
|
func (to *TLSObfs) Write(b []byte) (int, error) {
|
||||||
|
length := len(b)
|
||||||
|
for i := 0; i < length; i += chunkSize {
|
||||||
|
end := i + chunkSize
|
||||||
|
if end > length {
|
||||||
|
end = length
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := to.write(b[i:end])
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return length, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (to *TLSObfs) write(b []byte) (int, error) {
|
||||||
|
if to.firstRequest {
|
||||||
|
helloMsg := makeClientHelloMsg(b, to.server)
|
||||||
|
_, err := to.Conn.Write(helloMsg)
|
||||||
|
to.firstRequest = false
|
||||||
|
return len(b), err
|
||||||
|
}
|
||||||
|
|
||||||
|
size := bufPool.Get().([]byte)
|
||||||
|
binary.BigEndian.PutUint16(size[:2], uint16(len(b)))
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
buf.Write([]byte{0x17, 0x03, 0x03})
|
||||||
|
buf.Write(size[:2])
|
||||||
|
buf.Write(b)
|
||||||
|
_, err := to.Conn.Write(buf.Bytes())
|
||||||
|
bufPool.Put(size[:cap(size)])
|
||||||
|
return len(b), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTLSObfs return a SimpleObfs
|
||||||
|
func NewTLSObfs(conn net.Conn, server string) net.Conn {
|
||||||
|
return &TLSObfs{
|
||||||
|
Conn: conn,
|
||||||
|
server: server,
|
||||||
|
firstRequest: true,
|
||||||
|
firstResponse: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeClientHelloMsg(data []byte, server string) []byte {
|
||||||
|
random := make([]byte, 28)
|
||||||
|
sessionID := make([]byte, 32)
|
||||||
|
rand.Read(random)
|
||||||
|
rand.Read(sessionID)
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
|
||||||
|
// handshake, TLS 1.0 version, length
|
||||||
|
buf.WriteByte(22)
|
||||||
|
buf.Write([]byte{0x03, 0x01})
|
||||||
|
length := uint16(212 + len(data) + len(server))
|
||||||
|
buf.WriteByte(byte(length >> 8))
|
||||||
|
buf.WriteByte(byte(length & 0xff))
|
||||||
|
|
||||||
|
// clientHello, length, TLS 1.2 version
|
||||||
|
buf.WriteByte(1)
|
||||||
|
buf.WriteByte(0)
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(208+len(data)+len(server)))
|
||||||
|
buf.Write([]byte{0x03, 0x03})
|
||||||
|
|
||||||
|
// random with timestamp, sid len, sid
|
||||||
|
binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix()))
|
||||||
|
buf.Write(random)
|
||||||
|
buf.WriteByte(32)
|
||||||
|
buf.Write(sessionID)
|
||||||
|
|
||||||
|
// cipher suites
|
||||||
|
buf.Write([]byte{0x00, 0x38})
|
||||||
|
buf.Write([]byte{
|
||||||
|
0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f,
|
||||||
|
0x00, 0x9e, 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a,
|
||||||
|
0xc0, 0x14, 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0x9d, 0x00, 0x9c, 0x00, 0x3d,
|
||||||
|
0x00, 0x3c, 0x00, 0x35, 0x00, 0x2f, 0x00, 0xff,
|
||||||
|
})
|
||||||
|
|
||||||
|
// compression
|
||||||
|
buf.Write([]byte{0x01, 0x00})
|
||||||
|
|
||||||
|
// extension length
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(79+len(data)+len(server)))
|
||||||
|
|
||||||
|
// session ticket
|
||||||
|
buf.Write([]byte{0x00, 0x23})
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(len(data)))
|
||||||
|
buf.Write(data)
|
||||||
|
|
||||||
|
// server name
|
||||||
|
buf.Write([]byte{0x00, 0x00})
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(len(server)+5))
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(len(server)+3))
|
||||||
|
buf.WriteByte(0)
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(len(server)))
|
||||||
|
buf.Write([]byte(server))
|
||||||
|
|
||||||
|
// ec_point
|
||||||
|
buf.Write([]byte{0x00, 0x0b, 0x00, 0x04, 0x03, 0x01, 0x00, 0x02})
|
||||||
|
|
||||||
|
// groups
|
||||||
|
buf.Write([]byte{0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18})
|
||||||
|
|
||||||
|
// signature
|
||||||
|
buf.Write([]byte{
|
||||||
|
0x00, 0x0d, 0x00, 0x20, 0x00, 0x1e, 0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05,
|
||||||
|
0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0x03, 0x01,
|
||||||
|
0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03,
|
||||||
|
})
|
||||||
|
|
||||||
|
// encrypt then mac
|
||||||
|
buf.Write([]byte{0x00, 0x16, 0x00, 0x00})
|
||||||
|
|
||||||
|
// extended master secret
|
||||||
|
buf.Write([]byte{0x00, 0x17, 0x00, 0x00})
|
||||||
|
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
115
component/vmess/aead.go
Normal file
115
component/vmess/aead.go
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
package vmess
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/cipher"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type aeadWriter struct {
|
||||||
|
io.Writer
|
||||||
|
cipher.AEAD
|
||||||
|
nonce [32]byte
|
||||||
|
count uint16
|
||||||
|
iv []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAEADWriter(w io.Writer, aead cipher.AEAD, iv []byte) *aeadWriter {
|
||||||
|
return &aeadWriter{Writer: w, AEAD: aead, iv: iv}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *aeadWriter) Write(b []byte) (n int, err error) {
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
defer bufPool.Put(buf[:cap(buf)])
|
||||||
|
length := len(b)
|
||||||
|
for {
|
||||||
|
if length == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
readLen := chunkSize - w.Overhead()
|
||||||
|
if length < readLen {
|
||||||
|
readLen = length
|
||||||
|
}
|
||||||
|
payloadBuf := buf[lenSize : lenSize+chunkSize-w.Overhead()]
|
||||||
|
copy(payloadBuf, b[n:n+readLen])
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint16(buf[:lenSize], uint16(readLen+w.Overhead()))
|
||||||
|
binary.BigEndian.PutUint16(w.nonce[:2], w.count)
|
||||||
|
copy(w.nonce[2:], w.iv[2:12])
|
||||||
|
|
||||||
|
w.Seal(payloadBuf[:0], w.nonce[:w.NonceSize()], payloadBuf[:readLen], nil)
|
||||||
|
w.count++
|
||||||
|
|
||||||
|
_, err = w.Writer.Write(buf[:lenSize+readLen+w.Overhead()])
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
n += readLen
|
||||||
|
length -= readLen
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type aeadReader struct {
|
||||||
|
io.Reader
|
||||||
|
cipher.AEAD
|
||||||
|
nonce [32]byte
|
||||||
|
buf []byte
|
||||||
|
offset int
|
||||||
|
iv []byte
|
||||||
|
sizeBuf []byte
|
||||||
|
count uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAEADReader(r io.Reader, aead cipher.AEAD, iv []byte) *aeadReader {
|
||||||
|
return &aeadReader{Reader: r, AEAD: aead, iv: iv, sizeBuf: make([]byte, lenSize)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *aeadReader) Read(b []byte) (int, error) {
|
||||||
|
if r.buf != nil {
|
||||||
|
n := copy(b, r.buf[r.offset:])
|
||||||
|
r.offset += n
|
||||||
|
if r.offset == len(r.buf) {
|
||||||
|
bufPool.Put(r.buf[:cap(r.buf)])
|
||||||
|
r.buf = nil
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := io.ReadFull(r.Reader, r.sizeBuf)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
size := int(binary.BigEndian.Uint16(r.sizeBuf))
|
||||||
|
if size > maxSize {
|
||||||
|
return 0, errors.New("Buffer is larger than standard")
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
_, err = io.ReadFull(r.Reader, buf[:size])
|
||||||
|
if err != nil {
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint16(r.nonce[:2], r.count)
|
||||||
|
copy(r.nonce[2:], r.iv[2:12])
|
||||||
|
|
||||||
|
_, err = r.Open(buf[:0], r.nonce[:r.NonceSize()], buf[:size], nil)
|
||||||
|
r.count++
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
realLen := size - r.Overhead()
|
||||||
|
n := copy(b, buf[:realLen])
|
||||||
|
if len(b) >= realLen {
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
r.offset = n
|
||||||
|
r.buf = buf[:realLen]
|
||||||
|
return n, nil
|
||||||
|
}
|
103
component/vmess/chunk.go
Normal file
103
component/vmess/chunk.go
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
package vmess
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
lenSize = 2
|
||||||
|
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
|
||||||
|
maxSize = 17 * 1024 // 2 + chunkSize + aead.Overhead()
|
||||||
|
)
|
||||||
|
|
||||||
|
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, maxSize) }}
|
||||||
|
|
||||||
|
type chunkReader struct {
|
||||||
|
io.Reader
|
||||||
|
buf []byte
|
||||||
|
sizeBuf []byte
|
||||||
|
offset int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newChunkReader(reader io.Reader) *chunkReader {
|
||||||
|
return &chunkReader{Reader: reader, sizeBuf: make([]byte, lenSize)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newChunkWriter(writer io.WriteCloser) *chunkWriter {
|
||||||
|
return &chunkWriter{Writer: writer}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cr *chunkReader) Read(b []byte) (int, error) {
|
||||||
|
if cr.buf != nil {
|
||||||
|
n := copy(b, cr.buf[cr.offset:])
|
||||||
|
cr.offset += n
|
||||||
|
if cr.offset == len(cr.buf) {
|
||||||
|
bufPool.Put(cr.buf[:cap(cr.buf)])
|
||||||
|
cr.buf = nil
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := io.ReadFull(cr.Reader, cr.sizeBuf)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
size := int(binary.BigEndian.Uint16(cr.sizeBuf))
|
||||||
|
if size > maxSize {
|
||||||
|
return 0, errors.New("Buffer is larger than standard")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(b) >= size {
|
||||||
|
_, err := io.ReadFull(cr.Reader, b[:size])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return size, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
_, err = io.ReadFull(cr.Reader, buf[:size])
|
||||||
|
if err != nil {
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
n := copy(b, cr.buf[:])
|
||||||
|
cr.offset = n
|
||||||
|
cr.buf = buf[:size]
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type chunkWriter struct {
|
||||||
|
io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cw *chunkWriter) Write(b []byte) (n int, err error) {
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
defer bufPool.Put(buf[:cap(buf)])
|
||||||
|
length := len(b)
|
||||||
|
for {
|
||||||
|
if length == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
readLen := chunkSize
|
||||||
|
if length < chunkSize {
|
||||||
|
readLen = length
|
||||||
|
}
|
||||||
|
payloadBuf := buf[lenSize : lenSize+chunkSize]
|
||||||
|
copy(payloadBuf, b[n:n+readLen])
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint16(buf[:lenSize], uint16(readLen))
|
||||||
|
_, err = cw.Writer.Write(buf[:lenSize+readLen])
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
n += readLen
|
||||||
|
length -= readLen
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
212
component/vmess/conn.go
Normal file
212
component/vmess/conn.go
Normal file
@ -0,0 +1,212 @@
|
|||||||
|
package vmess
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"hash/fnv"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/chacha20poly1305"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn wrapper a net.Conn with vmess protocol
|
||||||
|
type Conn struct {
|
||||||
|
net.Conn
|
||||||
|
reader io.Reader
|
||||||
|
writer io.Writer
|
||||||
|
dst *DstAddr
|
||||||
|
id *ID
|
||||||
|
reqBodyIV []byte
|
||||||
|
reqBodyKey []byte
|
||||||
|
respBodyIV []byte
|
||||||
|
respBodyKey []byte
|
||||||
|
respV byte
|
||||||
|
security byte
|
||||||
|
|
||||||
|
sent bool
|
||||||
|
received bool
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *Conn) Read(b []byte) (int, error) {
|
||||||
|
if vc.received {
|
||||||
|
return vc.reader.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := vc.recvResponse(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
vc.received = true
|
||||||
|
return vc.reader.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *Conn) sendRequest() error {
|
||||||
|
timestamp := time.Now()
|
||||||
|
|
||||||
|
h := hmac.New(md5.New, vc.id.UUID.Bytes())
|
||||||
|
binary.Write(h, binary.BigEndian, uint64(timestamp.Unix()))
|
||||||
|
_, err := vc.Conn.Write(h.Sum(nil))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
|
||||||
|
// Ver IV Key V Opt
|
||||||
|
buf.WriteByte(Version)
|
||||||
|
buf.Write(vc.reqBodyIV[:])
|
||||||
|
buf.Write(vc.reqBodyKey[:])
|
||||||
|
buf.WriteByte(vc.respV)
|
||||||
|
buf.WriteByte(OptionChunkStream)
|
||||||
|
|
||||||
|
p := rand.Intn(16)
|
||||||
|
// P Sec Reserve Cmd
|
||||||
|
buf.WriteByte(byte(p<<4) | byte(vc.security))
|
||||||
|
buf.WriteByte(0)
|
||||||
|
buf.WriteByte(CommandTCP)
|
||||||
|
|
||||||
|
// Port AddrType Addr
|
||||||
|
binary.Write(buf, binary.BigEndian, uint16(vc.dst.Port))
|
||||||
|
buf.WriteByte(vc.dst.AddrType)
|
||||||
|
buf.Write(vc.dst.Addr)
|
||||||
|
|
||||||
|
// padding
|
||||||
|
if p > 0 {
|
||||||
|
padding := make([]byte, p)
|
||||||
|
rand.Read(padding)
|
||||||
|
buf.Write(padding)
|
||||||
|
}
|
||||||
|
|
||||||
|
fnv1a := fnv.New32a()
|
||||||
|
fnv1a.Write(buf.Bytes())
|
||||||
|
buf.Write(fnv1a.Sum(nil))
|
||||||
|
|
||||||
|
block, err := aes.NewCipher(vc.id.CmdKey)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
stream := cipher.NewCFBEncrypter(block, hashTimestamp(timestamp))
|
||||||
|
stream.XORKeyStream(buf.Bytes(), buf.Bytes())
|
||||||
|
_, err = vc.Conn.Write(buf.Bytes())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *Conn) recvResponse() error {
|
||||||
|
block, err := aes.NewCipher(vc.respBodyKey[:])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
stream := cipher.NewCFBDecrypter(block, vc.respBodyIV[:])
|
||||||
|
buf := make([]byte, 4)
|
||||||
|
_, err = io.ReadFull(vc.Conn, buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
stream.XORKeyStream(buf, buf)
|
||||||
|
|
||||||
|
if buf[0] != vc.respV {
|
||||||
|
return errors.New("unexpected response header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[2] != 0 {
|
||||||
|
return errors.New("dynamic port is not supported now")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashTimestamp(t time.Time) []byte {
|
||||||
|
md5hash := md5.New()
|
||||||
|
ts := make([]byte, 8)
|
||||||
|
binary.BigEndian.PutUint64(ts, uint64(t.Unix()))
|
||||||
|
md5hash.Write(ts)
|
||||||
|
md5hash.Write(ts)
|
||||||
|
md5hash.Write(ts)
|
||||||
|
md5hash.Write(ts)
|
||||||
|
return md5hash.Sum(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newConn return a Conn instance
|
||||||
|
func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
||||||
|
randBytes := make([]byte, 33)
|
||||||
|
rand.Read(randBytes)
|
||||||
|
reqBodyIV := make([]byte, 16)
|
||||||
|
reqBodyKey := make([]byte, 16)
|
||||||
|
copy(reqBodyIV[:], randBytes[:16])
|
||||||
|
copy(reqBodyKey[:], randBytes[16:32])
|
||||||
|
respV := randBytes[32]
|
||||||
|
|
||||||
|
respBodyKey := md5.Sum(reqBodyKey[:])
|
||||||
|
respBodyIV := md5.Sum(reqBodyIV[:])
|
||||||
|
|
||||||
|
var writer io.Writer
|
||||||
|
var reader io.Reader
|
||||||
|
switch security {
|
||||||
|
case SecurityNone:
|
||||||
|
reader = newChunkReader(conn)
|
||||||
|
writer = newChunkWriter(conn)
|
||||||
|
case SecurityAES128GCM:
|
||||||
|
block, _ := aes.NewCipher(reqBodyKey[:])
|
||||||
|
aead, _ := cipher.NewGCM(block)
|
||||||
|
writer = newAEADWriter(conn, aead, reqBodyIV[:])
|
||||||
|
|
||||||
|
block, _ = aes.NewCipher(respBodyKey[:])
|
||||||
|
aead, _ = cipher.NewGCM(block)
|
||||||
|
reader = newAEADReader(conn, aead, respBodyIV[:])
|
||||||
|
case SecurityCHACHA20POLY1305:
|
||||||
|
key := make([]byte, 32)
|
||||||
|
t := md5.Sum(reqBodyKey[:])
|
||||||
|
copy(key, t[:])
|
||||||
|
t = md5.Sum(key[:16])
|
||||||
|
copy(key[16:], t[:])
|
||||||
|
aead, _ := chacha20poly1305.New(key)
|
||||||
|
writer = newAEADWriter(conn, aead, reqBodyIV[:])
|
||||||
|
|
||||||
|
t = md5.Sum(respBodyKey[:])
|
||||||
|
copy(key, t[:])
|
||||||
|
t = md5.Sum(key[:16])
|
||||||
|
copy(key[16:], t[:])
|
||||||
|
aead, _ = chacha20poly1305.New(key)
|
||||||
|
reader = newAEADReader(conn, aead, respBodyIV[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Conn{
|
||||||
|
Conn: conn,
|
||||||
|
id: id,
|
||||||
|
dst: dst,
|
||||||
|
reqBodyIV: reqBodyIV,
|
||||||
|
reqBodyKey: reqBodyKey,
|
||||||
|
respV: respV,
|
||||||
|
respBodyIV: respBodyIV[:],
|
||||||
|
respBodyKey: respBodyKey[:],
|
||||||
|
reader: reader,
|
||||||
|
writer: writer,
|
||||||
|
security: security,
|
||||||
|
}
|
||||||
|
}
|
55
component/vmess/user.go
Normal file
55
component/vmess/user.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package vmess
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ID cmdKey length
|
||||||
|
const (
|
||||||
|
IDBytesLen = 16
|
||||||
|
)
|
||||||
|
|
||||||
|
// The ID of en entity, in the form of a UUID.
|
||||||
|
type ID struct {
|
||||||
|
UUID *uuid.UUID
|
||||||
|
CmdKey []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// newID returns an ID with given UUID.
|
||||||
|
func newID(uuid *uuid.UUID) *ID {
|
||||||
|
id := &ID{UUID: uuid, CmdKey: make([]byte, IDBytesLen)}
|
||||||
|
md5hash := md5.New()
|
||||||
|
md5hash.Write(uuid.Bytes())
|
||||||
|
md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
|
||||||
|
md5hash.Sum(id.CmdKey[:0])
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextID(u *uuid.UUID) *uuid.UUID {
|
||||||
|
md5hash := md5.New()
|
||||||
|
md5hash.Write(u.Bytes())
|
||||||
|
md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81"))
|
||||||
|
var newid uuid.UUID
|
||||||
|
for {
|
||||||
|
md5hash.Sum(newid[:0])
|
||||||
|
if !bytes.Equal(newid.Bytes(), u.Bytes()) {
|
||||||
|
return &newid
|
||||||
|
}
|
||||||
|
md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAlterIDs(primary *ID, alterIDCount uint16) []*ID {
|
||||||
|
alterIDs := make([]*ID, alterIDCount)
|
||||||
|
prevID := primary.UUID
|
||||||
|
for idx := range alterIDs {
|
||||||
|
newid := nextID(prevID)
|
||||||
|
alterIDs[idx] = &ID{UUID: newid, CmdKey: primary.CmdKey[:]}
|
||||||
|
prevID = newid
|
||||||
|
}
|
||||||
|
alterIDs = append(alterIDs, primary)
|
||||||
|
return alterIDs
|
||||||
|
}
|
173
component/vmess/vmess.go
Normal file
173
component/vmess/vmess.go
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
package vmess
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Version of vmess
|
||||||
|
const Version byte = 1
|
||||||
|
|
||||||
|
// Request Options
|
||||||
|
const (
|
||||||
|
OptionChunkStream byte = 1
|
||||||
|
OptionChunkMasking byte = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
// Security type vmess
|
||||||
|
type Security = byte
|
||||||
|
|
||||||
|
// Cipher types
|
||||||
|
const (
|
||||||
|
SecurityAES128GCM Security = 3
|
||||||
|
SecurityCHACHA20POLY1305 Security = 4
|
||||||
|
SecurityNone Security = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
// CipherMapping return
|
||||||
|
var CipherMapping = map[string]byte{
|
||||||
|
"none": SecurityNone,
|
||||||
|
"aes-128-gcm": SecurityAES128GCM,
|
||||||
|
"chacha20-poly1305": SecurityCHACHA20POLY1305,
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
clientSessionCache tls.ClientSessionCache
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
// Command types
|
||||||
|
const (
|
||||||
|
CommandTCP byte = 1
|
||||||
|
CommandUDP byte = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// Addr types
|
||||||
|
const (
|
||||||
|
AtypIPv4 byte = 1
|
||||||
|
AtypDomainName byte = 2
|
||||||
|
AtypIPv6 byte = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
// DstAddr store destination address
|
||||||
|
type DstAddr struct {
|
||||||
|
AddrType byte
|
||||||
|
Addr []byte
|
||||||
|
Port uint
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client is vmess connection generator
|
||||||
|
type Client struct {
|
||||||
|
user []*ID
|
||||||
|
uuid *uuid.UUID
|
||||||
|
security Security
|
||||||
|
tls bool
|
||||||
|
host string
|
||||||
|
wsConfig *websocketConfig
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config of vmess
|
||||||
|
type Config struct {
|
||||||
|
UUID string
|
||||||
|
AlterID uint16
|
||||||
|
Security string
|
||||||
|
TLS bool
|
||||||
|
HostName string
|
||||||
|
Port string
|
||||||
|
NetWork string
|
||||||
|
WebSocketPath string
|
||||||
|
SkipCertVerify bool
|
||||||
|
SessionCacahe tls.ClientSessionCache
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return a Conn with net.Conn and DstAddr
|
||||||
|
func (c *Client) New(conn net.Conn, dst *DstAddr) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
r := rand.Intn(len(c.user))
|
||||||
|
if c.wsConfig != nil {
|
||||||
|
conn, err = newWebsocketConn(conn, c.wsConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else if c.tls {
|
||||||
|
conn = tls.Client(conn, c.tlsConfig)
|
||||||
|
}
|
||||||
|
return newConn(conn, c.user[r], dst, c.security), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient return Client instance
|
||||||
|
func NewClient(config Config) (*Client, error) {
|
||||||
|
uid, err := uuid.FromString(config.UUID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var security Security
|
||||||
|
switch config.Security {
|
||||||
|
case "aes-128-gcm":
|
||||||
|
security = SecurityAES128GCM
|
||||||
|
case "chacha20-poly1305":
|
||||||
|
security = SecurityCHACHA20POLY1305
|
||||||
|
case "none":
|
||||||
|
security = SecurityNone
|
||||||
|
case "auto":
|
||||||
|
security = SecurityCHACHA20POLY1305
|
||||||
|
if runtime.GOARCH == "amd64" || runtime.GOARCH == "s390x" || runtime.GOARCH == "arm64" {
|
||||||
|
security = SecurityAES128GCM
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Unknown security type: %s", config.Security)
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.NetWork != "" && config.NetWork != "ws" {
|
||||||
|
return nil, fmt.Errorf("Unknown network type: %s", config.NetWork)
|
||||||
|
}
|
||||||
|
|
||||||
|
host := net.JoinHostPort(config.HostName, config.Port)
|
||||||
|
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if config.TLS {
|
||||||
|
tlsConfig = &tls.Config{
|
||||||
|
ServerName: config.HostName,
|
||||||
|
InsecureSkipVerify: config.SkipCertVerify,
|
||||||
|
ClientSessionCache: config.SessionCacahe,
|
||||||
|
}
|
||||||
|
if tlsConfig.ClientSessionCache == nil {
|
||||||
|
tlsConfig.ClientSessionCache = getClientSessionCache()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var wsConfig *websocketConfig
|
||||||
|
if config.NetWork == "ws" {
|
||||||
|
wsConfig = &websocketConfig{
|
||||||
|
host: host,
|
||||||
|
path: config.WebSocketPath,
|
||||||
|
tls: config.TLS,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Client{
|
||||||
|
user: newAlterIDs(newID(&uid), config.AlterID),
|
||||||
|
uuid: &uid,
|
||||||
|
security: security,
|
||||||
|
tls: config.TLS,
|
||||||
|
host: host,
|
||||||
|
wsConfig: wsConfig,
|
||||||
|
tlsConfig: tlsConfig,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getClientSessionCache() tls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
clientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return clientSessionCache
|
||||||
|
}
|
143
component/vmess/websocket.go
Normal file
143
component/vmess/websocket.go
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
package vmess
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
type websocketConn struct {
|
||||||
|
conn *websocket.Conn
|
||||||
|
reader io.Reader
|
||||||
|
remoteAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
type websocketConfig struct {
|
||||||
|
host string
|
||||||
|
path string
|
||||||
|
tls bool
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read implements net.Conn.Read()
|
||||||
|
func (wsc *websocketConn) Read(b []byte) (int, error) {
|
||||||
|
for {
|
||||||
|
reader, err := wsc.getReader()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
nBytes, err := reader.Read(b)
|
||||||
|
if err == io.EOF {
|
||||||
|
wsc.reader = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return nBytes, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write implements io.Writer.
|
||||||
|
func (wsc *websocketConn) Write(b []byte) (int, error) {
|
||||||
|
if err := wsc.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) Close() error {
|
||||||
|
var errors []string
|
||||||
|
if err := wsc.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
}
|
||||||
|
if err := wsc.conn.Close(); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
}
|
||||||
|
if len(errors) > 0 {
|
||||||
|
return fmt.Errorf("Failed to close connection: %s", strings.Join(errors, ","))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) getReader() (io.Reader, error) {
|
||||||
|
if wsc.reader != nil {
|
||||||
|
return wsc.reader, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, reader, err := wsc.conn.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
wsc.reader = reader
|
||||||
|
return reader, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) LocalAddr() net.Addr {
|
||||||
|
return wsc.conn.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) RemoteAddr() net.Addr {
|
||||||
|
return wsc.remoteAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) SetDeadline(t time.Time) error {
|
||||||
|
if err := wsc.SetReadDeadline(t); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return wsc.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
return wsc.conn.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsc *websocketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
return wsc.conn.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newWebsocketConn(conn net.Conn, c *websocketConfig) (net.Conn, error) {
|
||||||
|
dialer := &websocket.Dialer{
|
||||||
|
NetDial: func(network, addr string) (net.Conn, error) {
|
||||||
|
return conn, nil
|
||||||
|
},
|
||||||
|
ReadBufferSize: 4 * 1024,
|
||||||
|
WriteBufferSize: 4 * 1024,
|
||||||
|
HandshakeTimeout: time.Second * 8,
|
||||||
|
}
|
||||||
|
|
||||||
|
scheme := "ws"
|
||||||
|
if c.tls {
|
||||||
|
scheme = "wss"
|
||||||
|
dialer.TLSClientConfig = c.tlsConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
host, port, err := net.SplitHostPort(c.host)
|
||||||
|
if (scheme == "ws" && port != "80") || (scheme == "wss" && port != "443") {
|
||||||
|
host = c.host
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := url.URL{
|
||||||
|
Scheme: scheme,
|
||||||
|
Host: host,
|
||||||
|
Path: c.path,
|
||||||
|
}
|
||||||
|
|
||||||
|
wsConn, resp, err := dialer.Dial(uri.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
var reason string
|
||||||
|
if resp != nil {
|
||||||
|
reason = resp.Status
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("Dial %s error: %s", host, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &websocketConn{
|
||||||
|
conn: wsConn,
|
||||||
|
remoteAddr: conn.RemoteAddr(),
|
||||||
|
}, nil
|
||||||
|
}
|
410
config/config.go
Normal file
410
config/config.go
Normal file
@ -0,0 +1,410 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/dns"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
R "github.com/Dreamacro/clash/rules"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
|
yaml "gopkg.in/yaml.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// General config
|
||||||
|
type General struct {
|
||||||
|
Port int `json:"port"`
|
||||||
|
SocksPort int `json:"socks-port"`
|
||||||
|
RedirPort int `json:"redir-port"`
|
||||||
|
AllowLan bool `json:"allow-lan"`
|
||||||
|
Mode T.Mode `json:"mode"`
|
||||||
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
|
ExternalController string `json:"external-controller,omitempty"`
|
||||||
|
Secret string `json:"secret,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DNS config
|
||||||
|
type DNS struct {
|
||||||
|
Enable bool `yaml:"enable"`
|
||||||
|
IPv6 bool `yaml:"ipv6"`
|
||||||
|
NameServer []dns.NameServer `yaml:"nameserver"`
|
||||||
|
Fallback []dns.NameServer `yaml:"fallback"`
|
||||||
|
Listen string `yaml:"listen"`
|
||||||
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config is clash config manager
|
||||||
|
type Config struct {
|
||||||
|
General *General
|
||||||
|
DNS *DNS
|
||||||
|
Rules []C.Rule
|
||||||
|
Proxies map[string]C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
type rawDNS struct {
|
||||||
|
Enable bool `yaml:"enable"`
|
||||||
|
IPv6 bool `yaml:"ipv6"`
|
||||||
|
NameServer []string `yaml:"nameserver"`
|
||||||
|
Fallback []string `yaml:"fallback"`
|
||||||
|
Listen string `yaml:"listen"`
|
||||||
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type rawConfig struct {
|
||||||
|
Port int `yaml:"port"`
|
||||||
|
SocksPort int `yaml:"socks-port"`
|
||||||
|
RedirPort int `yaml:"redir-port"`
|
||||||
|
AllowLan bool `yaml:"allow-lan"`
|
||||||
|
Mode T.Mode `yaml:"mode"`
|
||||||
|
LogLevel log.LogLevel `yaml:"log-level"`
|
||||||
|
ExternalController string `yaml:"external-controller"`
|
||||||
|
Secret string `yaml:"secret"`
|
||||||
|
|
||||||
|
DNS *rawDNS `yaml:"dns"`
|
||||||
|
Proxy []map[string]interface{} `yaml:"Proxy"`
|
||||||
|
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
||||||
|
Rule []string `yaml:"Rule"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func readConfig(path string) (*rawConfig, error) {
|
||||||
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := ioutil.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(data) == 0 {
|
||||||
|
return nil, fmt.Errorf("Configuration file %s is empty", C.Path.Config())
|
||||||
|
}
|
||||||
|
|
||||||
|
// config with some default value
|
||||||
|
rawConfig := &rawConfig{
|
||||||
|
AllowLan: false,
|
||||||
|
Mode: T.Rule,
|
||||||
|
LogLevel: log.INFO,
|
||||||
|
Rule: []string{},
|
||||||
|
Proxy: []map[string]interface{}{},
|
||||||
|
ProxyGroup: []map[string]interface{}{},
|
||||||
|
DNS: &rawDNS{
|
||||||
|
Enable: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
||||||
|
return rawConfig, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse config
|
||||||
|
func Parse(path string) (*Config, error) {
|
||||||
|
config := &Config{}
|
||||||
|
|
||||||
|
rawCfg, err := readConfig(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
general, err := parseGeneral(rawCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.General = general
|
||||||
|
|
||||||
|
proxies, err := parseProxies(rawCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Proxies = proxies
|
||||||
|
|
||||||
|
rules, err := parseRules(rawCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.Rules = rules
|
||||||
|
|
||||||
|
dnsCfg, err := parseDNS(rawCfg.DNS)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config.DNS = dnsCfg
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGeneral(cfg *rawConfig) (*General, error) {
|
||||||
|
port := cfg.Port
|
||||||
|
socksPort := cfg.SocksPort
|
||||||
|
redirPort := cfg.RedirPort
|
||||||
|
allowLan := cfg.AllowLan
|
||||||
|
externalController := cfg.ExternalController
|
||||||
|
secret := cfg.Secret
|
||||||
|
mode := cfg.Mode
|
||||||
|
logLevel := cfg.LogLevel
|
||||||
|
|
||||||
|
general := &General{
|
||||||
|
Port: port,
|
||||||
|
SocksPort: socksPort,
|
||||||
|
RedirPort: redirPort,
|
||||||
|
AllowLan: allowLan,
|
||||||
|
Mode: mode,
|
||||||
|
LogLevel: logLevel,
|
||||||
|
ExternalController: externalController,
|
||||||
|
Secret: secret,
|
||||||
|
}
|
||||||
|
return general, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||||
|
proxies := make(map[string]C.Proxy)
|
||||||
|
proxiesConfig := cfg.Proxy
|
||||||
|
groupsConfig := cfg.ProxyGroup
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
proxies["DIRECT"] = adapters.NewDirect()
|
||||||
|
proxies["REJECT"] = adapters.NewReject()
|
||||||
|
|
||||||
|
// parse proxy
|
||||||
|
for idx, mapping := range proxiesConfig {
|
||||||
|
proxyType, existType := mapping["type"].(string)
|
||||||
|
if !existType {
|
||||||
|
return nil, fmt.Errorf("Proxy %d missing type", idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxy C.Proxy
|
||||||
|
var err error
|
||||||
|
switch proxyType {
|
||||||
|
case "ss":
|
||||||
|
ssOption := &adapters.ShadowSocksOption{}
|
||||||
|
err = decoder.Decode(mapping, ssOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = adapters.NewShadowSocks(*ssOption)
|
||||||
|
case "socks5":
|
||||||
|
socksOption := &adapters.Socks5Option{}
|
||||||
|
err = decoder.Decode(mapping, socksOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = adapters.NewSocks5(*socksOption)
|
||||||
|
case "http":
|
||||||
|
httpOption := &adapters.HttpOption{}
|
||||||
|
err = decoder.Decode(mapping, httpOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = adapters.NewHttp(*httpOption)
|
||||||
|
case "vmess":
|
||||||
|
vmessOption := &adapters.VmessOption{}
|
||||||
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = adapters.NewVmess(*vmessOption)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Proxy [%d]: %s", idx, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exist := proxies[proxy.Name()]; exist {
|
||||||
|
return nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
||||||
|
}
|
||||||
|
proxies[proxy.Name()] = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse proxy group
|
||||||
|
for idx, mapping := range groupsConfig {
|
||||||
|
groupType, existType := mapping["type"].(string)
|
||||||
|
groupName, existName := mapping["name"].(string)
|
||||||
|
if !existType && existName {
|
||||||
|
return nil, fmt.Errorf("ProxyGroup %d: missing type or name", idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exist := proxies[groupName]; exist {
|
||||||
|
return nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
||||||
|
}
|
||||||
|
var group C.Proxy
|
||||||
|
var err error
|
||||||
|
switch groupType {
|
||||||
|
case "url-test":
|
||||||
|
urlTestOption := &adapters.URLTestOption{}
|
||||||
|
err = decoder.Decode(mapping, urlTestOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
ps, err := getProxies(proxies, urlTestOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
|
}
|
||||||
|
group, err = adapters.NewURLTest(*urlTestOption, ps)
|
||||||
|
case "select":
|
||||||
|
selectorOption := &adapters.SelectorOption{}
|
||||||
|
err = decoder.Decode(mapping, selectorOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
ps, err := getProxies(proxies, selectorOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
|
}
|
||||||
|
group, err = adapters.NewSelector(selectorOption.Name, ps)
|
||||||
|
case "fallback":
|
||||||
|
fallbackOption := &adapters.FallbackOption{}
|
||||||
|
err = decoder.Decode(mapping, fallbackOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
ps, err := getProxies(proxies, fallbackOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||||
|
}
|
||||||
|
group, err = adapters.NewFallback(*fallbackOption, ps)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Proxy %s: %s", groupName, err.Error())
|
||||||
|
}
|
||||||
|
proxies[groupName] = group
|
||||||
|
}
|
||||||
|
|
||||||
|
var ps []C.Proxy
|
||||||
|
for _, v := range proxies {
|
||||||
|
ps = append(ps, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies["GLOBAL"], _ = adapters.NewSelector("GLOBAL", ps)
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRules(cfg *rawConfig) ([]C.Rule, error) {
|
||||||
|
rules := []C.Rule{}
|
||||||
|
|
||||||
|
rulesConfig := cfg.Rule
|
||||||
|
// parse rules
|
||||||
|
for idx, line := range rulesConfig {
|
||||||
|
rule := trimArr(strings.Split(line, ","))
|
||||||
|
var (
|
||||||
|
payload string
|
||||||
|
target string
|
||||||
|
)
|
||||||
|
|
||||||
|
switch len(rule) {
|
||||||
|
case 2:
|
||||||
|
target = rule[1]
|
||||||
|
case 3:
|
||||||
|
payload = rule[1]
|
||||||
|
target = rule[2]
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Rules[%d] error: format invalid", idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
rule = trimArr(rule)
|
||||||
|
switch rule[0] {
|
||||||
|
case "DOMAIN":
|
||||||
|
rules = append(rules, R.NewDomain(payload, target))
|
||||||
|
case "DOMAIN-SUFFIX":
|
||||||
|
rules = append(rules, R.NewDomainSuffix(payload, target))
|
||||||
|
case "DOMAIN-KEYWORD":
|
||||||
|
rules = append(rules, R.NewDomainKeyword(payload, target))
|
||||||
|
case "GEOIP":
|
||||||
|
rules = append(rules, R.NewGEOIP(payload, target))
|
||||||
|
case "IP-CIDR", "IP-CIDR6":
|
||||||
|
rules = append(rules, R.NewIPCIDR(payload, target))
|
||||||
|
case "MATCH":
|
||||||
|
fallthrough
|
||||||
|
case "FINAL":
|
||||||
|
rules = append(rules, R.NewFinal(target))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rules, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hostWithDefaultPort(host string, defPort string) (string, error) {
|
||||||
|
if !strings.Contains(host, ":") {
|
||||||
|
host += ":"
|
||||||
|
}
|
||||||
|
|
||||||
|
hostname, port, err := net.SplitHostPort(host)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if port == "" {
|
||||||
|
port = defPort
|
||||||
|
}
|
||||||
|
|
||||||
|
return net.JoinHostPort(hostname, port), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
||||||
|
nameservers := []dns.NameServer{}
|
||||||
|
log.Debugln("%#v", servers)
|
||||||
|
|
||||||
|
for idx, server := range servers {
|
||||||
|
// parse without scheme .e.g 8.8.8.8:53
|
||||||
|
if host, err := hostWithDefaultPort(server, "53"); err == nil {
|
||||||
|
nameservers = append(
|
||||||
|
nameservers,
|
||||||
|
dns.NameServer{Addr: host},
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err := url.Parse(server)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.Scheme != "tls" {
|
||||||
|
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
host, err := hostWithDefaultPort(u.Host, "853")
|
||||||
|
nameservers = append(
|
||||||
|
nameservers,
|
||||||
|
dns.NameServer{
|
||||||
|
Net: "tcp-tls",
|
||||||
|
Addr: host,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nameservers, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseDNS(cfg *rawDNS) (*DNS, error) {
|
||||||
|
if cfg.Enable && len(cfg.NameServer) == 0 {
|
||||||
|
return nil, fmt.Errorf("If DNS configuration is turned on, NameServer cannot be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsCfg := &DNS{
|
||||||
|
Enable: cfg.Enable,
|
||||||
|
Listen: cfg.Listen,
|
||||||
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
if nameserver, err := parseNameServer(cfg.NameServer); err == nil {
|
||||||
|
dnsCfg.NameServer = nameserver
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback, err := parseNameServer(cfg.Fallback); err == nil {
|
||||||
|
dnsCfg.Fallback = fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return dnsCfg, nil
|
||||||
|
}
|
81
config/initial.go
Normal file
81
config/initial.go
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"compress/gzip"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func downloadMMDB(path string) (err error) {
|
||||||
|
resp, err := http.Get("http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
gr, err := gzip.NewReader(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer gr.Close()
|
||||||
|
|
||||||
|
tr := tar.NewReader(gr)
|
||||||
|
for {
|
||||||
|
h, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.HasSuffix(h.Name, "GeoLite2-Country.mmdb") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, tr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init prepare necessary files
|
||||||
|
func Init(dir string) error {
|
||||||
|
// initial homedir
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
if err := os.MkdirAll(dir, 0777); err != nil {
|
||||||
|
return fmt.Errorf("Can't create config directory %s: %s", dir, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// initial config.yml
|
||||||
|
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
||||||
|
log.Info("Can't find config, create a empty file")
|
||||||
|
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// initial mmdb
|
||||||
|
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||||
|
log.Info("Can't find MMDB, start download")
|
||||||
|
err := downloadMMDB(C.Path.MMDB())
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Can't download MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
36
config/utils.go
Normal file
36
config/utils.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func trimArr(arr []string) (r []string) {
|
||||||
|
for _, e := range arr {
|
||||||
|
r = append(r, strings.Trim(e, " "))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
||||||
|
var ps []C.Proxy
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func or(pointers ...*int) *int {
|
||||||
|
for _, p := range pointers {
|
||||||
|
if p != nil {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pointers[len(pointers)-1]
|
||||||
|
}
|
@ -1,22 +1,63 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Adapter Type
|
||||||
|
const (
|
||||||
|
Direct AdapterType = iota
|
||||||
|
Fallback
|
||||||
|
Reject
|
||||||
|
Selector
|
||||||
|
Shadowsocks
|
||||||
|
Socks5
|
||||||
|
Http
|
||||||
|
URLTest
|
||||||
|
Vmess
|
||||||
|
)
|
||||||
|
|
||||||
type ProxyAdapter interface {
|
type ProxyAdapter interface {
|
||||||
ReadWriter() io.ReadWriter
|
|
||||||
Conn() net.Conn
|
Conn() net.Conn
|
||||||
Close()
|
Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServerAdapter interface {
|
type ServerAdapter interface {
|
||||||
Addr() *Addr
|
Metadata() *Metadata
|
||||||
Connect(ProxyAdapter)
|
|
||||||
Close()
|
Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
type Proxy interface {
|
type Proxy interface {
|
||||||
Generator(addr *Addr) (ProxyAdapter, error)
|
Name() string
|
||||||
|
Type() AdapterType
|
||||||
|
Generator(metadata *Metadata) (ProxyAdapter, error)
|
||||||
|
MarshalJSON() ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdapterType is enum of adapter type
|
||||||
|
type AdapterType int
|
||||||
|
|
||||||
|
func (at AdapterType) String() string {
|
||||||
|
switch at {
|
||||||
|
case Direct:
|
||||||
|
return "Direct"
|
||||||
|
case Fallback:
|
||||||
|
return "Fallback"
|
||||||
|
case Reject:
|
||||||
|
return "Reject"
|
||||||
|
case Selector:
|
||||||
|
return "Selector"
|
||||||
|
case Shadowsocks:
|
||||||
|
return "Shadowsocks"
|
||||||
|
case Socks5:
|
||||||
|
return "Socks5"
|
||||||
|
case Http:
|
||||||
|
return "Http"
|
||||||
|
case URLTest:
|
||||||
|
return "URLTest"
|
||||||
|
case Vmess:
|
||||||
|
return "Vmess"
|
||||||
|
default:
|
||||||
|
return "Unknow"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,107 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/tar"
|
|
||||||
"compress/gzip"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"os/user"
|
|
||||||
"path"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"gopkg.in/ini.v1"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
Name = "clash"
|
|
||||||
DefalutHTTPPort = "7890"
|
|
||||||
DefalutSOCKSPort = "7891"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
HomeDir string
|
|
||||||
ConfigPath string
|
|
||||||
MMDBPath string
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
currentUser, err := user.Current()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Can't get current user: %s", err.Error())
|
|
||||||
}
|
|
||||||
HomeDir = currentUser.HomeDir
|
|
||||||
|
|
||||||
dirPath := path.Join(HomeDir, ".config", Name)
|
|
||||||
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
|
|
||||||
if err := os.MkdirAll(dirPath, 0777); err != nil {
|
|
||||||
log.Fatalf("Can't create config directory %s: %s", dirPath, err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ConfigPath = path.Join(dirPath, "config.ini")
|
|
||||||
if _, err := os.Stat(ConfigPath); os.IsNotExist(err) {
|
|
||||||
log.Info("Can't find config, create a empty file")
|
|
||||||
os.OpenFile(ConfigPath, os.O_CREATE|os.O_WRONLY, 0644)
|
|
||||||
}
|
|
||||||
|
|
||||||
MMDBPath = path.Join(dirPath, "Country.mmdb")
|
|
||||||
if _, err := os.Stat(MMDBPath); os.IsNotExist(err) {
|
|
||||||
log.Info("Can't find MMDB, start download")
|
|
||||||
err := downloadMMDB(MMDBPath)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Can't download MMDB: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func downloadMMDB(path string) (err error) {
|
|
||||||
resp, err := http.Get("http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz")
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
gr, err := gzip.NewReader(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer gr.Close()
|
|
||||||
|
|
||||||
tr := tar.NewReader(gr)
|
|
||||||
for {
|
|
||||||
h, err := tr.Next()
|
|
||||||
if err == io.EOF {
|
|
||||||
break
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.HasSuffix(h.Name, "GeoLite2-Country.mmdb") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
_, err = io.Copy(f, tr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetConfig() (*ini.File, error) {
|
|
||||||
if _, err := os.Stat(ConfigPath); os.IsNotExist(err) {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return ini.LoadSources(
|
|
||||||
ini.LoadOptions{AllowBooleanKeys: true},
|
|
||||||
ConfigPath,
|
|
||||||
)
|
|
||||||
}
|
|
@ -10,8 +10,12 @@ const (
|
|||||||
AtypDomainName = 3
|
AtypDomainName = 3
|
||||||
AtypIPv6 = 4
|
AtypIPv6 = 4
|
||||||
|
|
||||||
TCP = iota
|
TCP NetWork = iota
|
||||||
UDP
|
UDP
|
||||||
|
|
||||||
|
HTTP SourceType = iota
|
||||||
|
SOCKS
|
||||||
|
REDIR
|
||||||
)
|
)
|
||||||
|
|
||||||
type NetWork int
|
type NetWork int
|
||||||
@ -23,16 +27,19 @@ func (n *NetWork) String() string {
|
|||||||
return "udp"
|
return "udp"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Addr is used to store connection address
|
type SourceType int
|
||||||
type Addr struct {
|
|
||||||
|
// Metadata is used to store connection address
|
||||||
|
type Metadata struct {
|
||||||
NetWork NetWork
|
NetWork NetWork
|
||||||
|
Source SourceType
|
||||||
AddrType int
|
AddrType int
|
||||||
Host string
|
Host string
|
||||||
IP *net.IP
|
IP *net.IP
|
||||||
Port string
|
Port string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (addr *Addr) String() string {
|
func (addr *Metadata) String() string {
|
||||||
if addr.Host == "" {
|
if addr.Host == "" {
|
||||||
return addr.IP.String()
|
return addr.IP.String()
|
||||||
}
|
}
|
49
constant/path.go
Normal file
49
constant/path.go
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package constant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/user"
|
||||||
|
P "path"
|
||||||
|
)
|
||||||
|
|
||||||
|
const Name = "clash"
|
||||||
|
|
||||||
|
// Path is used to get the configuration path
|
||||||
|
var Path *path
|
||||||
|
|
||||||
|
type path struct {
|
||||||
|
homedir string
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
currentUser, err := user.Current()
|
||||||
|
var homedir string
|
||||||
|
if err != nil {
|
||||||
|
dir := os.Getenv("HOME")
|
||||||
|
if dir == "" {
|
||||||
|
dir, _ = os.Getwd()
|
||||||
|
}
|
||||||
|
homedir = dir
|
||||||
|
} else {
|
||||||
|
homedir = currentUser.HomeDir
|
||||||
|
}
|
||||||
|
homedir = P.Join(homedir, ".config", Name)
|
||||||
|
Path = &path{homedir: homedir}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetHomeDir is used to set the configuration path
|
||||||
|
func SetHomeDir(root string) {
|
||||||
|
Path = &path{homedir: root}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *path) HomeDir() string {
|
||||||
|
return p.homedir
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *path) Config() string {
|
||||||
|
return P.Join(p.homedir, "config.yml")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *path) MMDB() string {
|
||||||
|
return P.Join(p.homedir, "Country.mmdb")
|
||||||
|
}
|
@ -2,7 +2,8 @@ package constant
|
|||||||
|
|
||||||
// Rule Type
|
// Rule Type
|
||||||
const (
|
const (
|
||||||
DomainSuffix RuleType = iota
|
Domain RuleType = iota
|
||||||
|
DomainSuffix
|
||||||
DomainKeyword
|
DomainKeyword
|
||||||
GEOIP
|
GEOIP
|
||||||
IPCIDR
|
IPCIDR
|
||||||
@ -11,8 +12,28 @@ const (
|
|||||||
|
|
||||||
type RuleType int
|
type RuleType int
|
||||||
|
|
||||||
|
func (rt RuleType) String() string {
|
||||||
|
switch rt {
|
||||||
|
case Domain:
|
||||||
|
return "Domain"
|
||||||
|
case DomainSuffix:
|
||||||
|
return "DomainSuffix"
|
||||||
|
case DomainKeyword:
|
||||||
|
return "DomainKeyword"
|
||||||
|
case GEOIP:
|
||||||
|
return "GEOIP"
|
||||||
|
case IPCIDR:
|
||||||
|
return "IPCIDR"
|
||||||
|
case FINAL:
|
||||||
|
return "FINAL"
|
||||||
|
default:
|
||||||
|
return "Unknow"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type Rule interface {
|
type Rule interface {
|
||||||
RuleType() RuleType
|
RuleType() RuleType
|
||||||
IsMatch(addr *Addr) bool
|
IsMatch(metadata *Metadata) bool
|
||||||
Adapter() string
|
Adapter() string
|
||||||
|
Payload() string
|
||||||
}
|
}
|
||||||
|
55
constant/traffic.go
Normal file
55
constant/traffic.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package constant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Traffic struct {
|
||||||
|
up chan int64
|
||||||
|
down chan int64
|
||||||
|
upCount int64
|
||||||
|
downCount int64
|
||||||
|
upTotal int64
|
||||||
|
downTotal int64
|
||||||
|
interval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Traffic) Up() chan<- int64 {
|
||||||
|
return t.up
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Traffic) Down() chan<- int64 {
|
||||||
|
return t.down
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Traffic) Now() (up int64, down int64) {
|
||||||
|
return t.upTotal, t.downTotal
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Traffic) handle() {
|
||||||
|
go t.handleCh(t.up, &t.upCount, &t.upTotal)
|
||||||
|
go t.handleCh(t.down, &t.downCount, &t.downTotal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Traffic) handleCh(ch <-chan int64, count *int64, total *int64) {
|
||||||
|
ticker := time.NewTicker(t.interval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case n := <-ch:
|
||||||
|
*count += n
|
||||||
|
case <-ticker.C:
|
||||||
|
*total = *count
|
||||||
|
*count = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTraffic(interval time.Duration) *Traffic {
|
||||||
|
t := &Traffic{
|
||||||
|
up: make(chan int64),
|
||||||
|
down: make(chan int64),
|
||||||
|
interval: interval,
|
||||||
|
}
|
||||||
|
go t.handle()
|
||||||
|
return t
|
||||||
|
}
|
259
dns/client.go
Normal file
259
dns/client.go
Normal file
@ -0,0 +1,259 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"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"
|
||||||
|
geoip2 "github.com/oschwald/geoip2-golang"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalSessionCache = tls.NewLRUClientSessionCache(64)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Main, Fallback []NameServer
|
||||||
|
IPv6 bool
|
||||||
|
EnhancedMode EnhancedMode
|
||||||
|
}
|
||||||
|
|
||||||
|
func transform(servers []NameServer) []*nameserver {
|
||||||
|
var ret []*nameserver
|
||||||
|
for _, s := range servers {
|
||||||
|
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
|
||||||
|
}
|
62
dns/server.go
Normal file
62
dns/server.go
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
address string
|
||||||
|
server = &Server{}
|
||||||
|
)
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
*D.Server
|
||||||
|
r *Resolver
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
|
||||||
|
msg, err := s.r.Exchange(r)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
D.HandleFailed(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msg.SetReply(r)
|
||||||
|
w.WriteMsg(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReCreateServer(addr string, resolver *Resolver) error {
|
||||||
|
if server.Server != nil {
|
||||||
|
server.Shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
if addr == address {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, port, err := net.SplitHostPort(addr)
|
||||||
|
if port == "0" || port == "" || err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
p, err := net.ListenUDP("udp", udpAddr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
address = addr
|
||||||
|
server = &Server{r: resolver}
|
||||||
|
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
server.ActivateAndServe()
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
}
|
89
dns/util.go
Normal file
89
dns/util.go
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
yaml "gopkg.in/yaml.v2"
|
||||||
|
|
||||||
|
D "github.com/miekg/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// EnhancedModeMapping is a mapping for EnhancedMode enum
|
||||||
|
EnhancedModeMapping = map[string]EnhancedMode{
|
||||||
|
NORMAL.String(): NORMAL,
|
||||||
|
FAKEIP.String(): FAKEIP,
|
||||||
|
MAPPING.String(): MAPPING,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
NORMAL EnhancedMode = iota
|
||||||
|
FAKEIP
|
||||||
|
MAPPING
|
||||||
|
)
|
||||||
|
|
||||||
|
type EnhancedMode int
|
||||||
|
|
||||||
|
// UnmarshalYAML unserialize EnhancedMode with yaml
|
||||||
|
func (e *EnhancedMode) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||||
|
var tp string
|
||||||
|
if err := unmarshal(&tp); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mode, exist := EnhancedModeMapping[tp]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid mode")
|
||||||
|
}
|
||||||
|
*e = mode
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalYAML serialize EnhancedMode with yaml
|
||||||
|
func (e EnhancedMode) MarshalYAML() ([]byte, error) {
|
||||||
|
return yaml.Marshal(e.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON unserialize EnhancedMode with json
|
||||||
|
func (e *EnhancedMode) UnmarshalJSON(data []byte) error {
|
||||||
|
var tp string
|
||||||
|
json.Unmarshal(data, &tp)
|
||||||
|
mode, exist := EnhancedModeMapping[tp]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid mode")
|
||||||
|
}
|
||||||
|
*e = mode
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON serialize EnhancedMode with json
|
||||||
|
func (e EnhancedMode) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(e.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e EnhancedMode) String() string {
|
||||||
|
switch e {
|
||||||
|
case NORMAL:
|
||||||
|
return "normal"
|
||||||
|
case FAKEIP:
|
||||||
|
return "fakeip"
|
||||||
|
case MAPPING:
|
||||||
|
return "redir-host"
|
||||||
|
default:
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
|
||||||
|
if len(msg.Answer) == 0 {
|
||||||
|
log.Debugln("[DNS] answer length is zero: %#v", msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ttl := time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
||||||
|
c.Put(key, msg, ttl)
|
||||||
|
}
|
BIN
docs/logo.png
Executable file
BIN
docs/logo.png
Executable file
Binary file not shown.
After Width: | Height: | Size: 14 KiB |
20
go.mod
Normal file
20
go.mod
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
module github.com/Dreamacro/clash
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/Dreamacro/go-shadowsocks2 v0.1.2
|
||||||
|
github.com/eapache/queue v1.1.0 // indirect
|
||||||
|
github.com/go-chi/chi v3.3.3+incompatible
|
||||||
|
github.com/go-chi/cors v1.0.0
|
||||||
|
github.com/go-chi/render v1.0.1
|
||||||
|
github.com/gofrs/uuid v3.1.0+incompatible
|
||||||
|
github.com/gorilla/websocket v1.4.0
|
||||||
|
github.com/miekg/dns v1.1.0
|
||||||
|
github.com/oschwald/geoip2-golang v1.2.1
|
||||||
|
github.com/oschwald/maxminddb-golang v1.3.0 // indirect
|
||||||
|
github.com/sirupsen/logrus v1.2.0
|
||||||
|
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85
|
||||||
|
golang.org/x/net v0.0.0-20181108082009-03003ca0c849 // indirect
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect
|
||||||
|
gopkg.in/eapache/channels.v1 v1.1.0
|
||||||
|
gopkg.in/yaml.v2 v2.2.2
|
||||||
|
)
|
49
go.sum
Normal file
49
go.sum
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
github.com/Dreamacro/go-shadowsocks2 v0.1.2 h1:8KgWbwAw5PJF+i6F3tI2iW/Em9WDtAuDG4obot8bGLM=
|
||||||
|
github.com/Dreamacro/go-shadowsocks2 v0.1.2/go.mod h1:J5YbNUiKtaD7EJmQ4O9ruUTY9+IgrflPgm63K1nUE0I=
|
||||||
|
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/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/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
|
||||||
|
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 v3.3.3+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/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/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1OvJns=
|
||||||
|
github.com/gofrs/uuid v3.1.0+incompatible h1:q2rtkjaKT4YEr6E1kamy0Ha4RtepWlQBedyHx0uzKwA=
|
||||||
|
github.com/gofrs/uuid v3.1.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.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||||
|
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/miekg/dns v1.1.0 h1:yv9O9RJbvVFkvW8PKYqp4x7HQkc5RWwmUY/L8MdUaIg=
|
||||||
|
github.com/miekg/dns v1.1.0/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||||
|
github.com/oschwald/geoip2-golang v1.2.1 h1:3iz+jmeJc6fuCyWeKgtXSXu7+zvkxJbHFXkMT5FVebU=
|
||||||
|
github.com/oschwald/geoip2-golang v1.2.1/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
||||||
|
github.com/oschwald/maxminddb-golang v1.3.0 h1:oTh8IBSj10S5JNlUDg5WjJ1QdBMdeaZIkPEVfESSWgE=
|
||||||
|
github.com/oschwald/maxminddb-golang v1.3.0/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY=
|
||||||
|
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/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
|
||||||
|
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||||
|
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/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
|
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
|
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 h1:et7+NAX3lLIk5qUCTA9QelBjGE/NkhzYw/mhnr0s7nI=
|
||||||
|
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
|
golang.org/x/net v0.0.0-20181108082009-03003ca0c849 h1:FSqE2GGG7wzsYUsWiQ8MZrvEd1EOyU3NCF0AW3Wtltg=
|
||||||
|
golang.org/x/net v0.0.0-20181108082009-03003ca0c849/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ=
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20181005133103-4497e2df6f9e h1:EfdBzeKbFSvOjoIqSZcfS8wp0FBLokGBEs9lz1OtSg0=
|
||||||
|
golang.org/x/sys v0.0.0-20181005133103-4497e2df6f9e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
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/eapache/channels.v1 v1.1.0 h1:5bGAyKKvyCTWjSj7mhefG6Lc68VyN4MH1v8/7OoeeB4=
|
||||||
|
gopkg.in/eapache/channels.v1 v1.1.0/go.mod h1:BHIBujSvu9yMTrTYbTCjDD43gUhtmaOtTWDe7sTv1js=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
101
hub/executor/executor.go
Normal file
101
hub/executor/executor.go
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
package executor
|
||||||
|
|
||||||
|
import (
|
||||||
|
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/config"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/dns"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
P "github.com/Dreamacro/clash/proxy"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parse config with default config path
|
||||||
|
func Parse() (*config.Config, error) {
|
||||||
|
return ParseWithPath(C.Path.Config())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseWithPath parse config with custom config path
|
||||||
|
func ParseWithPath(path string) (*config.Config, error) {
|
||||||
|
return config.Parse(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyConfig dispatch configure to all parts
|
||||||
|
func ApplyConfig(cfg *config.Config, force bool) {
|
||||||
|
if force {
|
||||||
|
updateGeneral(cfg.General)
|
||||||
|
}
|
||||||
|
updateProxies(cfg.Proxies)
|
||||||
|
updateRules(cfg.Rules)
|
||||||
|
updateGeneral(cfg.General)
|
||||||
|
updateDNS(cfg.DNS)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetGeneral() *config.General {
|
||||||
|
ports := P.GetPorts()
|
||||||
|
return &config.General{
|
||||||
|
Port: ports.Port,
|
||||||
|
SocksPort: ports.SocksPort,
|
||||||
|
RedirPort: ports.RedirPort,
|
||||||
|
AllowLan: P.AllowLan(),
|
||||||
|
Mode: T.Instance().Mode(),
|
||||||
|
LogLevel: log.Level(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateDNS(c *config.DNS) {
|
||||||
|
if c.Enable == false {
|
||||||
|
T.Instance().SetResolver(nil)
|
||||||
|
dns.ReCreateServer("", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r := dns.New(dns.Config{
|
||||||
|
Main: c.NameServer,
|
||||||
|
Fallback: c.Fallback,
|
||||||
|
IPv6: c.IPv6,
|
||||||
|
EnhancedMode: c.EnhancedMode,
|
||||||
|
})
|
||||||
|
T.Instance().SetResolver(r)
|
||||||
|
dns.ReCreateServer(c.Listen, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateProxies(proxies map[string]C.Proxy) {
|
||||||
|
tunnel := T.Instance()
|
||||||
|
oldProxies := tunnel.Proxies()
|
||||||
|
|
||||||
|
// close old goroutine
|
||||||
|
for _, proxy := range oldProxies {
|
||||||
|
switch raw := proxy.(type) {
|
||||||
|
case *adapters.URLTest:
|
||||||
|
raw.Close()
|
||||||
|
case *adapters.Fallback:
|
||||||
|
raw.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tunnel.UpdateProxies(proxies)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateRules(rules []C.Rule) {
|
||||||
|
T.Instance().UpdateRules(rules)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateGeneral(general *config.General) {
|
||||||
|
log.SetLevel(general.LogLevel)
|
||||||
|
T.Instance().SetMode(general.Mode)
|
||||||
|
|
||||||
|
allowLan := general.AllowLan
|
||||||
|
|
||||||
|
P.SetAllowLan(allowLan)
|
||||||
|
if err := P.ReCreateHTTP(general.Port); err != nil {
|
||||||
|
log.Errorln("Start HTTP server error: %s", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := P.ReCreateSocks(general.SocksPort); err != nil {
|
||||||
|
log.Errorln("Start SOCKS5 server error: %s", err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := P.ReCreateRedir(general.RedirPort); err != nil {
|
||||||
|
log.Errorln("Start Redir server error: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
21
hub/hub.go
Normal file
21
hub/hub.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package hub
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/hub/executor"
|
||||||
|
"github.com/Dreamacro/clash/hub/route"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parse call at the beginning of clash
|
||||||
|
func Parse() error {
|
||||||
|
cfg, err := executor.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.General.ExternalController != "" {
|
||||||
|
go route.Start(cfg.General.ExternalController, cfg.General.Secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.ApplyConfig(cfg, true)
|
||||||
|
return nil
|
||||||
|
}
|
102
hub/route/configs.go
Normal file
102
hub/route/configs.go
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/hub/executor"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
P "github.com/Dreamacro/clash/proxy"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
func configRouter() http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", getConfigs)
|
||||||
|
r.Put("/", updateConfigs)
|
||||||
|
r.Patch("/", patchConfigs)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
type configSchema struct {
|
||||||
|
Port *int `json:"port"`
|
||||||
|
SocksPort *int `json:"socket-port"`
|
||||||
|
RedirPort *int `json:"redir-port"`
|
||||||
|
AllowLan *bool `json:"allow-lan"`
|
||||||
|
Mode *T.Mode `json:"mode"`
|
||||||
|
LogLevel *log.LogLevel `json:"log-level"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
general := executor.GetGeneral()
|
||||||
|
render.Respond(w, r, general)
|
||||||
|
}
|
||||||
|
|
||||||
|
func pointerOrDefault(p *int, def int) int {
|
||||||
|
if p != nil {
|
||||||
|
return *p
|
||||||
|
}
|
||||||
|
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
func patchConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
general := &configSchema{}
|
||||||
|
if err := render.DecodeJSON(r.Body, general); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if general.AllowLan != nil {
|
||||||
|
P.SetAllowLan(*general.AllowLan)
|
||||||
|
}
|
||||||
|
|
||||||
|
ports := P.GetPorts()
|
||||||
|
P.ReCreateHTTP(pointerOrDefault(general.Port, ports.Port))
|
||||||
|
P.ReCreateSocks(pointerOrDefault(general.SocksPort, ports.SocksPort))
|
||||||
|
P.ReCreateRedir(pointerOrDefault(general.RedirPort, ports.RedirPort))
|
||||||
|
|
||||||
|
if general.Mode != nil {
|
||||||
|
T.Instance().SetMode(*general.Mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
if general.LogLevel != nil {
|
||||||
|
log.SetLevel(*general.LogLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
type updateConfigRequest struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
req := updateConfigRequest{}
|
||||||
|
if err := render.DecodeJSON(r.Body, &req); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !filepath.IsAbs(req.Path) {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, newError("path is not a absoluted path"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
force := r.URL.Query().Get("force") == "true"
|
||||||
|
cfg, err := executor.ParseWithPath(req.Path)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, newError(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.ApplyConfig(cfg, force)
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
12
hub/route/ctxkeys.go
Normal file
12
hub/route/ctxkeys.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
var (
|
||||||
|
CtxKeyProxyName = contextKey("proxy name")
|
||||||
|
CtxKeyProxy = contextKey("proxy")
|
||||||
|
)
|
||||||
|
|
||||||
|
type contextKey string
|
||||||
|
|
||||||
|
func (c contextKey) String() string {
|
||||||
|
return "clash context key " + string(c)
|
||||||
|
}
|
22
hub/route/errors.go
Normal file
22
hub/route/errors.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUnauthorized = newError("Unauthorized")
|
||||||
|
ErrBadRequest = newError("Body invalid")
|
||||||
|
ErrForbidden = newError("Forbidden")
|
||||||
|
ErrNotFound = newError("Resource not found")
|
||||||
|
ErrRequestTimeout = newError("Timeout")
|
||||||
|
)
|
||||||
|
|
||||||
|
// HTTPError is custom HTTP error for API
|
||||||
|
type HTTPError struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *HTTPError) Error() string {
|
||||||
|
return e.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
func newError(msg string) *HTTPError {
|
||||||
|
return &HTTPError{Message: msg}
|
||||||
|
}
|
137
hub/route/proxies.go
Normal file
137
hub/route/proxies.go
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
A "github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
func proxyRouter() http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", getProxies)
|
||||||
|
|
||||||
|
r.Route("/{name}", func(r chi.Router) {
|
||||||
|
r.Use(parseProxyName, findProxyByName)
|
||||||
|
r.Get("/", getProxy)
|
||||||
|
r.Get("/delay", getProxyDelay)
|
||||||
|
r.Put("/", updateProxy)
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// When name is composed of a partial escape string, Golang does not unescape it
|
||||||
|
func parseProxyName(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
name := chi.URLParam(r, "name")
|
||||||
|
if newName, err := url.PathUnescape(name); err == nil {
|
||||||
|
name = newName
|
||||||
|
}
|
||||||
|
ctx := context.WithValue(r.Context(), CtxKeyProxyName, name)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func findProxyByName(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
name := r.Context().Value(CtxKeyProxyName).(string)
|
||||||
|
proxies := T.Instance().Proxies()
|
||||||
|
proxy, exist := proxies[name]
|
||||||
|
if !exist {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
render.Respond(w, r, ErrNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.WithValue(r.Context(), CtxKeyProxy, proxy)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxies(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxies := T.Instance().Proxies()
|
||||||
|
render.Respond(w, r, map[string]map[string]C.Proxy{
|
||||||
|
"proxies": proxies,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||||
|
render.Respond(w, r, proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateProxyRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
|
req := UpdateProxyRequest{}
|
||||||
|
if err := render.DecodeJSON(r.Body, &req); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||||
|
|
||||||
|
selector, ok := proxy.(*A.Selector)
|
||||||
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := selector.Set(req.Name); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, newError(fmt.Sprintf("Selector update error: %s", err.Error())))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxyDelay(w http.ResponseWriter, r *http.Request) {
|
||||||
|
query := r.URL.Query()
|
||||||
|
url := query.Get("url")
|
||||||
|
timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||||
|
|
||||||
|
sigCh := make(chan int16)
|
||||||
|
go func() {
|
||||||
|
t, err := A.DelayTest(proxy, url)
|
||||||
|
if err != nil {
|
||||||
|
sigCh <- 0
|
||||||
|
}
|
||||||
|
sigCh <- t
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-time.After(time.Millisecond * time.Duration(timeout)):
|
||||||
|
w.WriteHeader(http.StatusRequestTimeout)
|
||||||
|
render.Respond(w, r, ErrRequestTimeout)
|
||||||
|
case t := <-sigCh:
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
40
hub/route/rules.go
Normal file
40
hub/route/rules.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ruleRouter() http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", getRules)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rule struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Payload string `json:"payload"`
|
||||||
|
Proxy string `json:"proxy"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getRules(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rawRules := T.Instance().Rules()
|
||||||
|
|
||||||
|
var rules []Rule
|
||||||
|
for _, rule := range rawRules {
|
||||||
|
rules = append(rules, Rule{
|
||||||
|
Type: rule.RuleType().String(),
|
||||||
|
Payload: rule.Payload(),
|
||||||
|
Proxy: rule.Adapter(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
render.Respond(w, r, map[string][]Rule{
|
||||||
|
"rules": rules,
|
||||||
|
})
|
||||||
|
}
|
140
hub/route/server.go
Normal file
140
hub/route/server.go
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
"github.com/go-chi/cors"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
serverSecret = ""
|
||||||
|
serverAddr = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
type Traffic struct {
|
||||||
|
Up int64 `json:"up"`
|
||||||
|
Down int64 `json:"down"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Start(addr string, secret string) {
|
||||||
|
if serverAddr != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
serverAddr = addr
|
||||||
|
serverSecret = secret
|
||||||
|
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
cors := cors.New(cors.Options{
|
||||||
|
AllowedOrigins: []string{"*"},
|
||||||
|
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||||
|
AllowedHeaders: []string{"Content-Type", "Authorization"},
|
||||||
|
MaxAge: 300,
|
||||||
|
})
|
||||||
|
|
||||||
|
r.Use(cors.Handler, authentication)
|
||||||
|
|
||||||
|
r.With(jsonContentType).Get("/traffic", traffic)
|
||||||
|
r.With(jsonContentType).Get("/logs", getLogs)
|
||||||
|
r.Mount("/configs", configRouter())
|
||||||
|
r.Mount("/proxies", proxyRouter())
|
||||||
|
r.Mount("/rules", ruleRouter())
|
||||||
|
|
||||||
|
log.Infoln("RESTful API listening at: %s", addr)
|
||||||
|
err := http.ListenAndServe(addr, r)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln("External controller error: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
header := r.Header.Get("Authorization")
|
||||||
|
text := strings.SplitN(header, " ", 2)
|
||||||
|
|
||||||
|
if serverSecret == "" {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hasUnvalidHeader := text[0] != "Bearer"
|
||||||
|
hasUnvalidSecret := len(text) == 2 && text[1] != serverSecret
|
||||||
|
if hasUnvalidHeader || hasUnvalidSecret {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
render.Respond(w, r, ErrUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
}
|
||||||
|
return http.HandlerFunc(fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func traffic(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
|
tick := time.NewTicker(time.Second)
|
||||||
|
t := T.Instance().Traffic()
|
||||||
|
for range tick.C {
|
||||||
|
up, down := t.Now()
|
||||||
|
if err := json.NewEncoder(w).Encode(Traffic{
|
||||||
|
Up: up,
|
||||||
|
Down: down,
|
||||||
|
}); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Log struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Payload string `json:"payload"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLogs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
levelText := r.URL.Query().Get("level")
|
||||||
|
if levelText == "" {
|
||||||
|
levelText = "info"
|
||||||
|
}
|
||||||
|
|
||||||
|
level, ok := log.LogLevelMapping[levelText]
|
||||||
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
render.Respond(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sub := log.Subscribe()
|
||||||
|
render.Status(r, http.StatusOK)
|
||||||
|
for elm := range sub {
|
||||||
|
log := elm.(*log.Event)
|
||||||
|
if log.LogLevel < level {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.NewEncoder(w).Encode(Log{
|
||||||
|
Type: log.Type(),
|
||||||
|
Payload: log.Payload,
|
||||||
|
}); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
}
|
||||||
|
}
|
73
log/level.go
Normal file
73
log/level.go
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
package log
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// LogLevelMapping is a mapping for LogLevel enum
|
||||||
|
LogLevelMapping = map[string]LogLevel{
|
||||||
|
ERROR.String(): ERROR,
|
||||||
|
WARNING.String(): WARNING,
|
||||||
|
INFO.String(): INFO,
|
||||||
|
DEBUG.String(): DEBUG,
|
||||||
|
SILENT.String(): SILENT,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEBUG LogLevel = iota
|
||||||
|
INFO
|
||||||
|
WARNING
|
||||||
|
ERROR
|
||||||
|
SILENT
|
||||||
|
)
|
||||||
|
|
||||||
|
type LogLevel int
|
||||||
|
|
||||||
|
// UnmarshalYAML unserialize LogLevel with yaml
|
||||||
|
func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||||
|
var tp string
|
||||||
|
unmarshal(&tp)
|
||||||
|
level, exist := LogLevelMapping[tp]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid mode")
|
||||||
|
}
|
||||||
|
*l = level
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON unserialize LogLevel with json
|
||||||
|
func (l *LogLevel) UnmarshalJSON(data []byte) error {
|
||||||
|
var tp string
|
||||||
|
json.Unmarshal(data, &tp)
|
||||||
|
level, exist := LogLevelMapping[tp]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid mode")
|
||||||
|
}
|
||||||
|
*l = level
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON serialize LogLevel with json
|
||||||
|
func (l LogLevel) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(l.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l LogLevel) String() string {
|
||||||
|
switch l {
|
||||||
|
case INFO:
|
||||||
|
return "info"
|
||||||
|
case WARNING:
|
||||||
|
return "warning"
|
||||||
|
case ERROR:
|
||||||
|
return "error"
|
||||||
|
case DEBUG:
|
||||||
|
return "debug"
|
||||||
|
case SILENT:
|
||||||
|
return "silent"
|
||||||
|
default:
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
}
|
93
log/log.go
Normal file
93
log/log.go
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
package log
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/observable"
|
||||||
|
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
logCh = make(chan interface{})
|
||||||
|
source = observable.NewObservable(logCh)
|
||||||
|
level = INFO
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
log.SetLevel(log.DebugLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Event struct {
|
||||||
|
LogLevel LogLevel
|
||||||
|
Payload string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Event) Type() string {
|
||||||
|
return e.LogLevel.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func Infoln(format string, v ...interface{}) {
|
||||||
|
event := newLog(INFO, format, v...)
|
||||||
|
logCh <- event
|
||||||
|
print(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Warnln(format string, v ...interface{}) {
|
||||||
|
event := newLog(WARNING, format, v...)
|
||||||
|
logCh <- event
|
||||||
|
print(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Errorln(format string, v ...interface{}) {
|
||||||
|
event := newLog(ERROR, format, v...)
|
||||||
|
logCh <- event
|
||||||
|
print(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Debugln(format string, v ...interface{}) {
|
||||||
|
event := newLog(DEBUG, format, v...)
|
||||||
|
logCh <- event
|
||||||
|
print(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Fatalln(format string, v ...interface{}) {
|
||||||
|
log.Fatalf(format, v...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Subscribe() observable.Subscription {
|
||||||
|
sub, _ := source.Subscribe()
|
||||||
|
return sub
|
||||||
|
}
|
||||||
|
|
||||||
|
func Level() LogLevel {
|
||||||
|
return level
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetLevel(newLevel LogLevel) {
|
||||||
|
level = newLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
func print(data *Event) {
|
||||||
|
if data.LogLevel < level {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch data.LogLevel {
|
||||||
|
case INFO:
|
||||||
|
log.Infoln(data.Payload)
|
||||||
|
case WARNING:
|
||||||
|
log.Warnln(data.Payload)
|
||||||
|
case ERROR:
|
||||||
|
log.Errorln(data.Payload)
|
||||||
|
case DEBUG:
|
||||||
|
log.Debugln(data.Payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLog(logLevel LogLevel, format string, v ...interface{}) *Event {
|
||||||
|
return &Event{
|
||||||
|
LogLevel: logLevel,
|
||||||
|
Payload: fmt.Sprintf(format, v...),
|
||||||
|
}
|
||||||
|
}
|
41
main.go
41
main.go
@ -1,42 +1,45 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"flag"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/config"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/proxy/http"
|
"github.com/Dreamacro/clash/hub"
|
||||||
"github.com/Dreamacro/clash/proxy/socks"
|
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
homedir string
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
flag.StringVar(&homedir, "d", "", "set configuration directory")
|
||||||
|
flag.Parse()
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
cfg, err := C.GetConfig()
|
if homedir != "" {
|
||||||
if err != nil {
|
if !filepath.IsAbs(homedir) {
|
||||||
log.Fatalf("Read config error: %s", err.Error())
|
currentDir, _ := os.Getwd()
|
||||||
|
homedir = filepath.Join(currentDir, homedir)
|
||||||
|
}
|
||||||
|
C.SetHomeDir(homedir)
|
||||||
}
|
}
|
||||||
|
|
||||||
port, socksPort := C.DefalutHTTPPort, C.DefalutSOCKSPort
|
if err := config.Init(C.Path.HomeDir()); err != nil {
|
||||||
section := cfg.Section("General")
|
log.Fatalf("Initial configuration directory error: %s", err.Error())
|
||||||
if key, err := section.GetKey("port"); err == nil {
|
|
||||||
port = key.Value()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if key, err := section.GetKey("socks-port"); err == nil {
|
if err := hub.Parse(); err != nil {
|
||||||
socksPort = key.Value()
|
|
||||||
}
|
|
||||||
|
|
||||||
err = tunnel.GetInstance().UpdateConfig()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Parse config error: %s", err.Error())
|
log.Fatalf("Parse config error: %s", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
go http.NewHttpProxy(port)
|
|
||||||
go socks.NewSocksProxy(socksPort)
|
|
||||||
|
|
||||||
sigCh := make(chan os.Signal, 1)
|
sigCh := make(chan os.Signal, 1)
|
||||||
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||||||
<-sigCh
|
<-sigCh
|
||||||
|
@ -1,18 +0,0 @@
|
|||||||
package observable
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Iterable <-chan interface{}
|
|
||||||
|
|
||||||
func NewIterable(any interface{}) (Iterable, error) {
|
|
||||||
switch any := any.(type) {
|
|
||||||
case chan interface{}:
|
|
||||||
return Iterable(any), nil
|
|
||||||
case <-chan interface{}:
|
|
||||||
return Iterable(any), nil
|
|
||||||
default:
|
|
||||||
return nil, errors.New("type error")
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
package observable
|
|
||||||
|
|
||||||
func mergeWithBytes(ch <-chan interface{}, buf []byte) chan interface{} {
|
|
||||||
out := make(chan interface{})
|
|
||||||
go func() {
|
|
||||||
defer close(out)
|
|
||||||
if len(buf) != 0 {
|
|
||||||
out <- buf
|
|
||||||
}
|
|
||||||
for elm := range ch {
|
|
||||||
out <- elm
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return out
|
|
||||||
}
|
|
@ -1,62 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type HttpAdapter struct {
|
|
||||||
addr *C.Addr
|
|
||||||
r *http.Request
|
|
||||||
w http.ResponseWriter
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HttpAdapter) Close() {
|
|
||||||
h.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HttpAdapter) Addr() *C.Addr {
|
|
||||||
return h.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HttpAdapter) Connect(proxy C.ProxyAdapter) {
|
|
||||||
req := http.Transport{
|
|
||||||
Dial: func(string, string) (net.Conn, error) {
|
|
||||||
return proxy.Conn(), nil
|
|
||||||
},
|
|
||||||
// from http.DefaultTransport
|
|
||||||
MaxIdleConns: 100,
|
|
||||||
IdleConnTimeout: 90 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
}
|
|
||||||
resp, err := req.RoundTrip(h.r)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
header := h.w.Header()
|
|
||||||
for k, vv := range resp.Header {
|
|
||||||
for _, v := range vv {
|
|
||||||
header.Add(k, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
h.w.WriteHeader(resp.StatusCode)
|
|
||||||
io.Copy(h.w, resp.Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHttp(host string, w http.ResponseWriter, r *http.Request) (*HttpAdapter, chan struct{}) {
|
|
||||||
done := make(chan struct{})
|
|
||||||
return &HttpAdapter{
|
|
||||||
addr: parseHttpAddr(host),
|
|
||||||
r: r,
|
|
||||||
w: w,
|
|
||||||
done: done,
|
|
||||||
}, done
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type HttpsAdapter struct {
|
|
||||||
addr *C.Addr
|
|
||||||
conn net.Conn
|
|
||||||
rw *bufio.ReadWriter
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HttpsAdapter) Close() {
|
|
||||||
h.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HttpsAdapter) Addr() *C.Addr {
|
|
||||||
return h.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HttpsAdapter) Connect(proxy C.ProxyAdapter) {
|
|
||||||
go io.Copy(h.conn, proxy.ReadWriter())
|
|
||||||
io.Copy(proxy.ReadWriter(), h.conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHttps(host string, conn net.Conn) *HttpsAdapter {
|
|
||||||
return &HttpsAdapter{
|
|
||||||
addr: parseHttpAddr(host),
|
|
||||||
conn: conn,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,86 +1,74 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"bufio"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/riobard/go-shadowsocks2/socks"
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
tun = tunnel.GetInstance()
|
tun = tunnel.Instance()
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewHttpProxy(port string) {
|
type HttpListener struct {
|
||||||
server := &http.Server{
|
net.Listener
|
||||||
Addr: fmt.Sprintf(":%s", port),
|
address string
|
||||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
closed bool
|
||||||
if r.Method == http.MethodConnect {
|
|
||||||
handleTunneling(w, r)
|
|
||||||
} else {
|
|
||||||
handleHTTP(w, r)
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
log.Infof("HTTP proxy :%s", port)
|
|
||||||
server.ListenAndServe()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleHTTP(w http.ResponseWriter, r *http.Request) {
|
func NewHttpProxy(addr string) (*HttpListener, error) {
|
||||||
addr := r.Host
|
l, err := net.Listen("tcp", addr)
|
||||||
// padding default port
|
|
||||||
if !strings.Contains(addr, ":") {
|
|
||||||
addr += ":80"
|
|
||||||
}
|
|
||||||
req, done := NewHttp(addr, w, r)
|
|
||||||
tun.Add(req)
|
|
||||||
<-done
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleTunneling(w http.ResponseWriter, r *http.Request) {
|
|
||||||
hijacker, ok := w.(http.Hijacker)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
conn, _, err := hijacker.Hijack()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
hl := &HttpListener{l, addr, false}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
log.Infoln("HTTP proxy listening at: %s", addr)
|
||||||
|
for {
|
||||||
|
c, err := hl.Accept()
|
||||||
|
if err != nil {
|
||||||
|
if hl.closed {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
go handleConn(c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return hl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *HttpListener) Close() {
|
||||||
|
l.closed = true
|
||||||
|
l.Listener.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *HttpListener) Address() string {
|
||||||
|
return l.address
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleConn(conn net.Conn) {
|
||||||
|
br := bufio.NewReader(conn)
|
||||||
|
request, err := http.ReadRequest(br)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// w.WriteHeader(http.StatusOK) doesn't works in Safari
|
|
||||||
conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
|
if request.Method == http.MethodConnect {
|
||||||
tun.Add(NewHttps(r.Host, conn))
|
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||||
}
|
if err != nil {
|
||||||
|
return
|
||||||
func parseHttpAddr(target string) *C.Addr {
|
}
|
||||||
host, port, _ := net.SplitHostPort(target)
|
tun.Add(adapters.NewHTTPS(request, conn))
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
return
|
||||||
var resolveIP *net.IP
|
}
|
||||||
if err == nil {
|
|
||||||
resolveIP = &ipAddr.IP
|
tun.Add(adapters.NewHTTP(request, conn))
|
||||||
}
|
|
||||||
|
|
||||||
var addType int
|
|
||||||
ip := net.ParseIP(host)
|
|
||||||
switch {
|
|
||||||
case ip == nil:
|
|
||||||
addType = socks.AtypDomainName
|
|
||||||
case ip.To4() == nil:
|
|
||||||
addType = socks.AtypIPv6
|
|
||||||
default:
|
|
||||||
addType = socks.AtypIPv4
|
|
||||||
}
|
|
||||||
|
|
||||||
return &C.Addr{
|
|
||||||
NetWork: C.TCP,
|
|
||||||
AddrType: addType,
|
|
||||||
Host: host,
|
|
||||||
IP: resolveIP,
|
|
||||||
Port: port,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
150
proxy/listener.go
Normal file
150
proxy/listener.go
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
package proxy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/proxy/http"
|
||||||
|
"github.com/Dreamacro/clash/proxy/redir"
|
||||||
|
"github.com/Dreamacro/clash/proxy/socks"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
allowLan = false
|
||||||
|
|
||||||
|
socksListener *socks.SockListener
|
||||||
|
httpListener *http.HttpListener
|
||||||
|
redirListener *redir.RedirListener
|
||||||
|
)
|
||||||
|
|
||||||
|
type listener interface {
|
||||||
|
Close()
|
||||||
|
Address() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Ports struct {
|
||||||
|
Port int `json:"port"`
|
||||||
|
SocksPort int `json:"socks-port"`
|
||||||
|
RedirPort int `json:"redir-port"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func AllowLan() bool {
|
||||||
|
return allowLan
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetAllowLan(al bool) {
|
||||||
|
allowLan = al
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReCreateHTTP(port int) error {
|
||||||
|
addr := genAddr(port, allowLan)
|
||||||
|
|
||||||
|
if httpListener != nil {
|
||||||
|
if httpListener.Address() == addr {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
httpListener.Close()
|
||||||
|
httpListener = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if portIsZero(addr) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
httpListener, err = http.NewHttpProxy(addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReCreateSocks(port int) error {
|
||||||
|
addr := genAddr(port, allowLan)
|
||||||
|
|
||||||
|
if socksListener != nil {
|
||||||
|
if socksListener.Address() == addr {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
socksListener.Close()
|
||||||
|
socksListener = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if portIsZero(addr) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
socksListener, err = socks.NewSocksProxy(addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReCreateRedir(port int) error {
|
||||||
|
addr := genAddr(port, allowLan)
|
||||||
|
|
||||||
|
if redirListener != nil {
|
||||||
|
if redirListener.Address() == addr {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
redirListener.Close()
|
||||||
|
redirListener = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if portIsZero(addr) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
redirListener, err = redir.NewRedirProxy(addr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPorts return the ports of proxy servers
|
||||||
|
func GetPorts() *Ports {
|
||||||
|
ports := &Ports{}
|
||||||
|
|
||||||
|
if httpListener != nil {
|
||||||
|
_, portStr, _ := net.SplitHostPort(httpListener.Address())
|
||||||
|
port, _ := strconv.Atoi(portStr)
|
||||||
|
ports.Port = port
|
||||||
|
}
|
||||||
|
|
||||||
|
if socksListener != nil {
|
||||||
|
_, portStr, _ := net.SplitHostPort(socksListener.Address())
|
||||||
|
port, _ := strconv.Atoi(portStr)
|
||||||
|
ports.SocksPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
if redirListener != nil {
|
||||||
|
_, portStr, _ := net.SplitHostPort(redirListener.Address())
|
||||||
|
port, _ := strconv.Atoi(portStr)
|
||||||
|
ports.RedirPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return ports
|
||||||
|
}
|
||||||
|
|
||||||
|
func portIsZero(addr string) bool {
|
||||||
|
_, port, err := net.SplitHostPort(addr)
|
||||||
|
if port == "0" || port == "" || err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func genAddr(port int, allowLan bool) string {
|
||||||
|
if allowLan {
|
||||||
|
return fmt.Sprintf(":%d", port)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("127.0.0.1:%d", port)
|
||||||
|
}
|
63
proxy/redir/tcp.go
Normal file
63
proxy/redir/tcp.go
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
tun = tunnel.Instance()
|
||||||
|
)
|
||||||
|
|
||||||
|
type RedirListener struct {
|
||||||
|
net.Listener
|
||||||
|
address string
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRedirProxy(addr string) (*RedirListener, error) {
|
||||||
|
l, err := net.Listen("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rl := &RedirListener{l, addr, false}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
log.Infoln("Redir proxy listening at: %s", addr)
|
||||||
|
for {
|
||||||
|
c, err := l.Accept()
|
||||||
|
if err != nil {
|
||||||
|
if rl.closed {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
go handleRedir(c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return rl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RedirListener) Close() {
|
||||||
|
l.closed = true
|
||||||
|
l.Listener.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RedirListener) Address() string {
|
||||||
|
return l.address
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleRedir(conn net.Conn) {
|
||||||
|
target, err := parserPacket(conn)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||||
|
tun.Add(adapters.NewSocket(target, conn, C.REDIR))
|
||||||
|
}
|
58
proxy/redir/tcp_darwin.go
Normal file
58
proxy/redir/tcp_darwin.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parserPacket(c net.Conn) (socks.Addr, error) {
|
||||||
|
const (
|
||||||
|
PfInout = 0
|
||||||
|
PfIn = 1
|
||||||
|
PfOut = 2
|
||||||
|
IOCOut = 0x40000000
|
||||||
|
IOCIn = 0x80000000
|
||||||
|
IOCInOut = IOCIn | IOCOut
|
||||||
|
IOCPARMMask = 0x1FFF
|
||||||
|
LEN = 4*16 + 4*4 + 4*1
|
||||||
|
// #define _IOC(inout,group,num,len) (inout | ((len & IOCPARMMask) << 16) | ((group) << 8) | (num))
|
||||||
|
// #define _IOWR(g,n,t) _IOC(IOCInOut, (g), (n), sizeof(t))
|
||||||
|
// #define DIOCNATLOOK _IOWR('D', 23, struct pfioc_natlook)
|
||||||
|
DIOCNATLOOK = IOCInOut | ((LEN & IOCPARMMask) << 16) | ('D' << 8) | 23
|
||||||
|
)
|
||||||
|
|
||||||
|
fd, err := syscall.Open("/dev/pf", 0, syscall.O_RDONLY)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer syscall.Close(fd)
|
||||||
|
|
||||||
|
nl := struct { // struct pfioc_natlook
|
||||||
|
saddr, daddr, rsaddr, rdaddr [16]byte
|
||||||
|
sxport, dxport, rsxport, rdxport [4]byte
|
||||||
|
af, proto, protoVariant, direction uint8
|
||||||
|
}{
|
||||||
|
af: syscall.AF_INET,
|
||||||
|
proto: syscall.IPPROTO_TCP,
|
||||||
|
direction: PfOut,
|
||||||
|
}
|
||||||
|
saddr := c.RemoteAddr().(*net.TCPAddr)
|
||||||
|
daddr := c.LocalAddr().(*net.TCPAddr)
|
||||||
|
copy(nl.saddr[:], saddr.IP)
|
||||||
|
copy(nl.daddr[:], daddr.IP)
|
||||||
|
nl.sxport[0], nl.sxport[1] = byte(saddr.Port>>8), byte(saddr.Port)
|
||||||
|
nl.dxport[0], nl.dxport[1] = byte(daddr.Port>>8), byte(daddr.Port)
|
||||||
|
|
||||||
|
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 {
|
||||||
|
return nil, errno
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := make([]byte, 1+net.IPv4len+2)
|
||||||
|
addr[0] = socks.AtypIPv4
|
||||||
|
copy(addr[1:1+net.IPv4len], nl.rdaddr[:4])
|
||||||
|
copy(addr[1+net.IPv4len:], nl.rdxport[:2])
|
||||||
|
return addr, nil
|
||||||
|
}
|
51
proxy/redir/tcp_linux.go
Normal file
51
proxy/redir/tcp_linux.go
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||||
|
)
|
||||||
|
|
||||||
|
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) (socks.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 socks.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) (socks.Addr, error) {
|
||||||
|
raw := syscall.RawSockaddrInet4{}
|
||||||
|
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 {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := make([]byte, 1+net.IPv4len+2)
|
||||||
|
addr[0] = socks.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
|
||||||
|
}
|
17
proxy/redir/tcp_linux_386.go
Normal file
17
proxy/redir/tcp_linux_386.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const GETSOCKOPT = 15 // https://golang.org/src/syscall/syscall_linux_386.go#L183
|
||||||
|
|
||||||
|
func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) error {
|
||||||
|
var a [6]uintptr
|
||||||
|
a[0], a[1], a[2], a[3], a[4], a[5] = a0, a1, a2, a3, a4, a5
|
||||||
|
if _, _, errno := syscall.Syscall6(syscall.SYS_SOCKETCALL, call, uintptr(unsafe.Pointer(&a)), 0, 0, 0, 0); errno != 0 {
|
||||||
|
return errno
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
14
proxy/redir/tcp_linux_other.go
Normal file
14
proxy/redir/tcp_linux_other.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
// +build linux,!386
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import "syscall"
|
||||||
|
|
||||||
|
const GETSOCKOPT = syscall.SYS_GETSOCKOPT
|
||||||
|
|
||||||
|
func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) error {
|
||||||
|
if _, _, errno := syscall.Syscall6(call, a0, a1, a2, a3, a4, a5); errno != 0 {
|
||||||
|
return errno
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
12
proxy/redir/tcp_windows.go
Normal file
12
proxy/redir/tcp_windows.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||||
|
return nil, errors.New("Windows not support yet")
|
||||||
|
}
|
@ -1,36 +1,57 @@
|
|||||||
package socks
|
package socks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/inbound"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/riobard/go-shadowsocks2/socks"
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
tun = tunnel.GetInstance()
|
tun = tunnel.Instance()
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewSocksProxy(port string) {
|
type SockListener struct {
|
||||||
l, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
|
net.Listener
|
||||||
defer l.Close()
|
address string
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSocksProxy(addr string) (*SockListener, error) {
|
||||||
|
l, err := net.Listen("tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return nil, err
|
||||||
}
|
}
|
||||||
log.Infof("SOCKS proxy :%s", port)
|
|
||||||
for {
|
sl := &SockListener{l, addr, false}
|
||||||
c, err := l.Accept()
|
go func() {
|
||||||
if err != nil {
|
log.Infoln("SOCKS proxy listening at: %s", addr)
|
||||||
continue
|
for {
|
||||||
|
c, err := l.Accept()
|
||||||
|
if err != nil {
|
||||||
|
if sl.closed {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
go handleSocks(c)
|
||||||
}
|
}
|
||||||
go handleSocks(c)
|
}()
|
||||||
}
|
|
||||||
|
return sl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *SockListener) Close() {
|
||||||
|
l.closed = true
|
||||||
|
l.Listener.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *SockListener) Address() string {
|
||||||
|
return l.address
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleSocks(conn net.Conn) {
|
func handleSocks(conn net.Conn) {
|
||||||
@ -40,59 +61,5 @@ func handleSocks(conn net.Conn) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||||
tun.Add(NewSocks(target, conn))
|
tun.Add(adapters.NewSocket(target, conn, C.SOCKS))
|
||||||
}
|
|
||||||
|
|
||||||
type SocksAdapter struct {
|
|
||||||
conn net.Conn
|
|
||||||
addr *C.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SocksAdapter) Close() {
|
|
||||||
s.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SocksAdapter) Addr() *C.Addr {
|
|
||||||
return s.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SocksAdapter) Connect(proxy C.ProxyAdapter) {
|
|
||||||
go io.Copy(s.conn, proxy.ReadWriter())
|
|
||||||
io.Copy(proxy.ReadWriter(), s.conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseSocksAddr(target socks.Addr) *C.Addr {
|
|
||||||
var host, port string
|
|
||||||
var ip net.IP
|
|
||||||
|
|
||||||
switch target[0] {
|
|
||||||
case socks.AtypDomainName:
|
|
||||||
host = string(target[2 : 2+target[1]])
|
|
||||||
port = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
|
||||||
if err == nil {
|
|
||||||
ip = ipAddr.IP
|
|
||||||
}
|
|
||||||
case socks.AtypIPv4:
|
|
||||||
ip = net.IP(target[1 : 1+net.IPv4len])
|
|
||||||
port = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
|
||||||
case socks.AtypIPv6:
|
|
||||||
ip = net.IP(target[1 : 1+net.IPv6len])
|
|
||||||
port = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
|
||||||
}
|
|
||||||
|
|
||||||
return &C.Addr{
|
|
||||||
NetWork: C.TCP,
|
|
||||||
AddrType: int(target[0]),
|
|
||||||
Host: host,
|
|
||||||
IP: &ip,
|
|
||||||
Port: port,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSocks(target socks.Addr, conn net.Conn) *SocksAdapter {
|
|
||||||
return &SocksAdapter{
|
|
||||||
conn: conn,
|
|
||||||
addr: parseSocksAddr(target),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
38
rules/domain.go
Normal file
38
rules/domain.go
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Domain struct {
|
||||||
|
domain string
|
||||||
|
adapter string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Domain) RuleType() C.RuleType {
|
||||||
|
return C.Domain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Domain) IsMatch(metadata *C.Metadata) bool {
|
||||||
|
if metadata.AddrType != C.AtypDomainName {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return metadata.Host == d.domain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Domain) Adapter() string {
|
||||||
|
return d.adapter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Domain) Payload() string {
|
||||||
|
return d.domain
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDomain(domain string, adapter string) *Domain {
|
||||||
|
return &Domain{
|
||||||
|
domain: strings.ToLower(domain),
|
||||||
|
adapter: adapter,
|
||||||
|
}
|
||||||
|
}
|
@ -15,11 +15,11 @@ func (dk *DomainKeyword) RuleType() C.RuleType {
|
|||||||
return C.DomainKeyword
|
return C.DomainKeyword
|
||||||
}
|
}
|
||||||
|
|
||||||
func (dk *DomainKeyword) IsMatch(addr *C.Addr) bool {
|
func (dk *DomainKeyword) IsMatch(metadata *C.Metadata) bool {
|
||||||
if addr.AddrType != C.AtypDomainName {
|
if metadata.AddrType != C.AtypDomainName {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
domain := addr.Host
|
domain := metadata.Host
|
||||||
return strings.Contains(domain, dk.keyword)
|
return strings.Contains(domain, dk.keyword)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,9 +27,13 @@ func (dk *DomainKeyword) Adapter() string {
|
|||||||
return dk.adapter
|
return dk.adapter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (dk *DomainKeyword) Payload() string {
|
||||||
|
return dk.keyword
|
||||||
|
}
|
||||||
|
|
||||||
func NewDomainKeyword(keyword string, adapter string) *DomainKeyword {
|
func NewDomainKeyword(keyword string, adapter string) *DomainKeyword {
|
||||||
return &DomainKeyword{
|
return &DomainKeyword{
|
||||||
keyword: keyword,
|
keyword: strings.ToLower(keyword),
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,11 @@ func (ds *DomainSuffix) RuleType() C.RuleType {
|
|||||||
return C.DomainSuffix
|
return C.DomainSuffix
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ds *DomainSuffix) IsMatch(addr *C.Addr) bool {
|
func (ds *DomainSuffix) IsMatch(metadata *C.Metadata) bool {
|
||||||
if addr.AddrType != C.AtypDomainName {
|
if metadata.AddrType != C.AtypDomainName {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
domain := addr.Host
|
domain := metadata.Host
|
||||||
return strings.HasSuffix(domain, "."+ds.suffix) || domain == ds.suffix
|
return strings.HasSuffix(domain, "."+ds.suffix) || domain == ds.suffix
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,9 +27,13 @@ func (ds *DomainSuffix) Adapter() string {
|
|||||||
return ds.adapter
|
return ds.adapter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ds *DomainSuffix) Payload() string {
|
||||||
|
return ds.suffix
|
||||||
|
}
|
||||||
|
|
||||||
func NewDomainSuffix(suffix string, adapter string) *DomainSuffix {
|
func NewDomainSuffix(suffix string, adapter string) *DomainSuffix {
|
||||||
return &DomainSuffix{
|
return &DomainSuffix{
|
||||||
suffix: suffix,
|
suffix: strings.ToLower(suffix),
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,7 @@ func (f *Final) RuleType() C.RuleType {
|
|||||||
return C.FINAL
|
return C.FINAL
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Final) IsMatch(addr *C.Addr) bool {
|
func (f *Final) IsMatch(metadata *C.Metadata) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -20,6 +20,10 @@ func (f *Final) Adapter() string {
|
|||||||
return f.adapter
|
return f.adapter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Final) Payload() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func NewFinal(adapter string) *Final {
|
func NewFinal(adapter string) *Final {
|
||||||
return &Final{
|
return &Final{
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
|
@ -1,21 +1,18 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
"github.com/oschwald/geoip2-golang"
|
"github.com/oschwald/geoip2-golang"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
var mmdb *geoip2.Reader
|
var (
|
||||||
|
mmdb *geoip2.Reader
|
||||||
func init() {
|
once sync.Once
|
||||||
var err error
|
)
|
||||||
mmdb, err = geoip2.Open(C.MMDBPath)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Can't load mmdb: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type GEOIP struct {
|
type GEOIP struct {
|
||||||
country string
|
country string
|
||||||
@ -26,11 +23,11 @@ func (g *GEOIP) RuleType() C.RuleType {
|
|||||||
return C.GEOIP
|
return C.GEOIP
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *GEOIP) IsMatch(addr *C.Addr) bool {
|
func (g *GEOIP) IsMatch(metadata *C.Metadata) bool {
|
||||||
if addr.IP == nil {
|
if metadata.IP == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
record, _ := mmdb.Country(*addr.IP)
|
record, _ := mmdb.Country(*metadata.IP)
|
||||||
return record.Country.IsoCode == g.country
|
return record.Country.IsoCode == g.country
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,7 +35,18 @@ func (g *GEOIP) Adapter() string {
|
|||||||
return g.adapter
|
return g.adapter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (g *GEOIP) Payload() string {
|
||||||
|
return g.country
|
||||||
|
}
|
||||||
|
|
||||||
func NewGEOIP(country string, adapter string) *GEOIP {
|
func NewGEOIP(country string, adapter string) *GEOIP {
|
||||||
|
once.Do(func() {
|
||||||
|
var err error
|
||||||
|
mmdb, err = geoip2.Open(C.Path.MMDB())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Can't load mmdb: %s", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
return &GEOIP{
|
return &GEOIP{
|
||||||
country: country,
|
country: country,
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
|
@ -15,16 +15,20 @@ func (i *IPCIDR) RuleType() C.RuleType {
|
|||||||
return C.IPCIDR
|
return C.IPCIDR
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) IsMatch(addr *C.Addr) bool {
|
func (i *IPCIDR) IsMatch(metadata *C.Metadata) bool {
|
||||||
if addr.IP == nil {
|
if metadata.IP == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return i.ipnet.Contains(*addr.IP)
|
return i.ipnet.Contains(*metadata.IP)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *IPCIDR) Adapter() string {
|
func (i *IPCIDR) Adapter() string {
|
||||||
return g.adapter
|
return i.adapter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *IPCIDR) Payload() string {
|
||||||
|
return i.ipnet.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewIPCIDR(s string, adapter string) *IPCIDR {
|
func NewIPCIDR(s string, adapter string) *IPCIDR {
|
||||||
|
91
tunnel/connection.go
Normal file
91
tunnel/connection.go
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
package tunnel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
host := req.Host
|
||||||
|
|
||||||
|
for {
|
||||||
|
req.Header.Set("Connection", "close")
|
||||||
|
req.RequestURI = ""
|
||||||
|
adapters.RemoveHopByHopHeaders(req.Header)
|
||||||
|
err := req.Write(conn)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
br := bufio.NewReader(conn)
|
||||||
|
resp, err := http.ReadResponse(br, req)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
adapters.RemoveHopByHopHeaders(resp.Header)
|
||||||
|
if resp.ContentLength >= 0 {
|
||||||
|
resp.Header.Set("Proxy-Connection", "keep-alive")
|
||||||
|
resp.Header.Set("Connection", "keep-alive")
|
||||||
|
resp.Header.Set("Keep-Alive", "timeout=4")
|
||||||
|
resp.Close = false
|
||||||
|
} else {
|
||||||
|
resp.Close = true
|
||||||
|
}
|
||||||
|
err = resp.Write(request.Conn())
|
||||||
|
if err != nil || resp.Close {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err = http.ReadRequest(bufio.NewReader(request.Conn()))
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sometimes firefox just open a socket to process multiple domains in HTTP
|
||||||
|
// The temporary solution is close connection when encountering different HOST
|
||||||
|
if req.Host != host {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) handleSOCKS(request *adapters.SocketAdapter, proxy C.ProxyAdapter) {
|
||||||
|
conn := newTrafficTrack(proxy.Conn(), t.traffic)
|
||||||
|
relay(request.Conn(), conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// relay copies between left and right bidirectionally.
|
||||||
|
func relay(leftConn, rightConn net.Conn) {
|
||||||
|
ch := make(chan error)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
_, err := io.CopyBuffer(leftConn, rightConn, buf)
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
leftConn.SetReadDeadline(time.Now())
|
||||||
|
ch <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
io.CopyBuffer(rightConn, leftConn, buf)
|
||||||
|
bufPool.Put(buf[:cap(buf)])
|
||||||
|
rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
@ -1,52 +0,0 @@
|
|||||||
package tunnel
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
INFO LogType = iota
|
|
||||||
WARNING
|
|
||||||
ERROR
|
|
||||||
DEBUG
|
|
||||||
)
|
|
||||||
|
|
||||||
type LogType int
|
|
||||||
|
|
||||||
type Log struct {
|
|
||||||
LogType LogType
|
|
||||||
Payload string
|
|
||||||
}
|
|
||||||
|
|
||||||
func print(data Log) {
|
|
||||||
switch data.LogType {
|
|
||||||
case INFO:
|
|
||||||
log.Infoln(data.Payload)
|
|
||||||
case WARNING:
|
|
||||||
log.Warnln(data.Payload)
|
|
||||||
case ERROR:
|
|
||||||
log.Errorln(data.Payload)
|
|
||||||
case DEBUG:
|
|
||||||
log.Debugln(data.Payload)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Tunnel) subscribeLogs() {
|
|
||||||
sub, err := t.observable.Subscribe()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Can't subscribe tunnel log: %s", err.Error())
|
|
||||||
}
|
|
||||||
for elm := range sub {
|
|
||||||
data := elm.(Log)
|
|
||||||
print(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newLog(logType LogType, format string, v ...interface{}) Log {
|
|
||||||
return Log{
|
|
||||||
LogType: logType,
|
|
||||||
Payload: fmt.Sprintf(format, v...),
|
|
||||||
}
|
|
||||||
}
|
|
65
tunnel/mode.go
Normal file
65
tunnel/mode.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
package tunnel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Mode int
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ModeMapping is a mapping for Mode enum
|
||||||
|
ModeMapping = map[string]Mode{
|
||||||
|
Global.String(): Global,
|
||||||
|
Rule.String(): Rule,
|
||||||
|
Direct.String(): Direct,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
Global Mode = iota
|
||||||
|
Rule
|
||||||
|
Direct
|
||||||
|
)
|
||||||
|
|
||||||
|
// UnmarshalJSON unserialize Mode
|
||||||
|
func (m *Mode) UnmarshalJSON(data []byte) error {
|
||||||
|
var tp string
|
||||||
|
json.Unmarshal(data, &tp)
|
||||||
|
mode, exist := ModeMapping[tp]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid mode")
|
||||||
|
}
|
||||||
|
*m = mode
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalYAML unserialize Mode with yaml
|
||||||
|
func (m *Mode) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||||
|
var tp string
|
||||||
|
unmarshal(&tp)
|
||||||
|
mode, exist := ModeMapping[tp]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid mode")
|
||||||
|
}
|
||||||
|
*m = mode
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON serialize Mode
|
||||||
|
func (m Mode) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(m.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Mode) String() string {
|
||||||
|
switch m {
|
||||||
|
case Global:
|
||||||
|
return "Global"
|
||||||
|
case Rule:
|
||||||
|
return "Rule"
|
||||||
|
case Direct:
|
||||||
|
return "Direct"
|
||||||
|
default:
|
||||||
|
return "Unknow"
|
||||||
|
}
|
||||||
|
}
|
195
tunnel/tunnel.go
195
tunnel/tunnel.go
@ -1,14 +1,14 @@
|
|||||||
package tunnel
|
package tunnel
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"net"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapters"
|
InboundAdapter "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/observable"
|
"github.com/Dreamacro/clash/dns"
|
||||||
R "github.com/Dreamacro/clash/rules"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"gopkg.in/eapache/channels.v1"
|
"gopkg.in/eapache/channels.v1"
|
||||||
)
|
)
|
||||||
@ -18,79 +18,66 @@ var (
|
|||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Tunnel handle proxy socket and HTTP/SOCKS socket
|
||||||
type Tunnel struct {
|
type Tunnel struct {
|
||||||
queue *channels.InfiniteChannel
|
queue *channels.InfiniteChannel
|
||||||
rules []C.Rule
|
rules []C.Rule
|
||||||
proxys map[string]C.Proxy
|
proxies map[string]C.Proxy
|
||||||
observable *observable.Observable
|
|
||||||
logCh chan interface{}
|
|
||||||
configLock *sync.RWMutex
|
configLock *sync.RWMutex
|
||||||
|
traffic *C.Traffic
|
||||||
|
resolver *dns.Resolver
|
||||||
|
|
||||||
|
// Outbound Rule
|
||||||
|
mode Mode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add request to queue
|
||||||
func (t *Tunnel) Add(req C.ServerAdapter) {
|
func (t *Tunnel) Add(req C.ServerAdapter) {
|
||||||
t.queue.In() <- req
|
t.queue.In() <- req
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) UpdateConfig() (err error) {
|
// Traffic return traffic of all connections
|
||||||
|
func (t *Tunnel) Traffic() *C.Traffic {
|
||||||
|
return t.traffic
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rules return all rules
|
||||||
|
func (t *Tunnel) Rules() []C.Rule {
|
||||||
|
return t.rules
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateRules handle update rules
|
||||||
|
func (t *Tunnel) UpdateRules(rules []C.Rule) {
|
||||||
t.configLock.Lock()
|
t.configLock.Lock()
|
||||||
defer t.configLock.Unlock()
|
t.rules = rules
|
||||||
|
t.configLock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
cfg, err := C.GetConfig()
|
// Proxies return all proxies
|
||||||
if err != nil {
|
func (t *Tunnel) Proxies() map[string]C.Proxy {
|
||||||
return
|
return t.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
// clear proxys and rules
|
// UpdateProxies handle update proxies
|
||||||
t.proxys = make(map[string]C.Proxy)
|
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy) {
|
||||||
t.rules = []C.Rule{}
|
t.configLock.Lock()
|
||||||
|
t.proxies = proxies
|
||||||
|
t.configLock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
proxys := cfg.Section("Proxy")
|
// Mode return current mode
|
||||||
rules := cfg.Section("Rule")
|
func (t *Tunnel) Mode() Mode {
|
||||||
|
return t.mode
|
||||||
|
}
|
||||||
|
|
||||||
// parse proxy
|
// SetMode change the mode of tunnel
|
||||||
for _, key := range proxys.Keys() {
|
func (t *Tunnel) SetMode(mode Mode) {
|
||||||
proxy := strings.Split(key.Value(), ",")
|
t.mode = mode
|
||||||
if len(proxy) == 0 {
|
}
|
||||||
continue
|
|
||||||
}
|
|
||||||
proxy = trimArr(proxy)
|
|
||||||
switch proxy[0] {
|
|
||||||
// ss, server, port, cipter, password
|
|
||||||
case "ss":
|
|
||||||
if len(proxy) < 5 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ssURL := fmt.Sprintf("ss://%s:%s@%s:%s", proxy[3], proxy[4], proxy[1], proxy[2])
|
|
||||||
t.proxys[key.Name()] = adapters.NewShadowSocks(ssURL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// init proxy
|
// SetResolver change the resolver of tunnel
|
||||||
t.proxys["DIRECT"] = adapters.NewDirect()
|
func (t *Tunnel) SetResolver(resolver *dns.Resolver) {
|
||||||
t.proxys["REJECT"] = adapters.NewReject()
|
t.resolver = resolver
|
||||||
|
|
||||||
// parse rules
|
|
||||||
for _, key := range rules.Keys() {
|
|
||||||
rule := strings.Split(key.Name(), ",")
|
|
||||||
if len(rule) < 3 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
rule = trimArr(rule)
|
|
||||||
switch rule[0] {
|
|
||||||
case "DOMAIN-SUFFIX":
|
|
||||||
t.rules = append(t.rules, R.NewDomainSuffix(rule[1], rule[2]))
|
|
||||||
case "DOMAIN-KEYWORD":
|
|
||||||
t.rules = append(t.rules, R.NewDomainKeyword(rule[1], rule[2]))
|
|
||||||
case "GEOIP":
|
|
||||||
t.rules = append(t.rules, R.NewGEOIP(rule[1], rule[2]))
|
|
||||||
case "IP-CIDR", "IP-CIDR6":
|
|
||||||
t.rules = append(t.rules, R.NewIPCIDR(rule[1], rule[2]))
|
|
||||||
case "FINAL":
|
|
||||||
t.rules = append(t.rules, R.NewFinal(rule[2]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) process() {
|
func (t *Tunnel) process() {
|
||||||
@ -102,55 +89,99 @@ func (t *Tunnel) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) resolveIP(host string) (net.IP, error) {
|
||||||
|
if t.resolver == nil {
|
||||||
|
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) handleConn(localConn C.ServerAdapter) {
|
||||||
defer localConn.Close()
|
defer localConn.Close()
|
||||||
addr := localConn.Addr()
|
metadata := localConn.Metadata()
|
||||||
proxy := t.match(addr)
|
|
||||||
remoConn, err := proxy.Generator(addr)
|
if metadata.Source == C.REDIR && t.resolver != nil {
|
||||||
|
host, exist := t.resolver.IPToHost(*metadata.IP)
|
||||||
|
if exist {
|
||||||
|
metadata.Host = host
|
||||||
|
metadata.AddrType = C.AtypDomainName
|
||||||
|
}
|
||||||
|
} 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
|
||||||
|
switch t.mode {
|
||||||
|
case Direct:
|
||||||
|
proxy = t.proxies["DIRECT"]
|
||||||
|
case Global:
|
||||||
|
proxy = t.proxies["GLOBAL"]
|
||||||
|
// Rule
|
||||||
|
default:
|
||||||
|
proxy = t.match(metadata)
|
||||||
|
}
|
||||||
|
remoConn, err := proxy.Generator(metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.logCh <- newLog(WARNING, "Proxy connect error: %s", err.Error())
|
log.Warnln("Proxy[%s] connect [%s] error: %s", proxy.Name(), metadata.String(), err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer remoConn.Close()
|
defer remoConn.Close()
|
||||||
|
|
||||||
localConn.Connect(remoConn)
|
switch adapter := localConn.(type) {
|
||||||
|
case *InboundAdapter.HTTPAdapter:
|
||||||
|
t.handleHTTP(adapter, remoConn)
|
||||||
|
case *InboundAdapter.SocketAdapter:
|
||||||
|
t.handleSOCKS(adapter, remoConn)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) match(addr *C.Addr) C.Proxy {
|
func (t *Tunnel) match(metadata *C.Metadata) C.Proxy {
|
||||||
t.configLock.RLock()
|
t.configLock.RLock()
|
||||||
defer t.configLock.RUnlock()
|
defer t.configLock.RUnlock()
|
||||||
|
|
||||||
for _, rule := range t.rules {
|
for _, rule := range t.rules {
|
||||||
if rule.IsMatch(addr) {
|
if rule.IsMatch(metadata) {
|
||||||
a, ok := t.proxys[rule.Adapter()]
|
a, ok := t.proxies[rule.Adapter()]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
t.logCh <- newLog(INFO, "%v match %d using %s", addr.String(), rule.RuleType(), rule.Adapter())
|
log.Infoln("%v match %s using %s", metadata.String(), rule.RuleType().String(), rule.Adapter())
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.logCh <- newLog(INFO, "don't find, direct")
|
log.Infoln("%v doesn't match any rule using DIRECT", metadata.String())
|
||||||
return t.proxys["DIRECT"]
|
return t.proxies["DIRECT"]
|
||||||
}
|
}
|
||||||
|
|
||||||
func newTunnel() *Tunnel {
|
func newTunnel() *Tunnel {
|
||||||
logCh := make(chan interface{})
|
return &Tunnel{
|
||||||
tunnel := &Tunnel{
|
|
||||||
queue: channels.NewInfiniteChannel(),
|
queue: channels.NewInfiniteChannel(),
|
||||||
proxys: make(map[string]C.Proxy),
|
proxies: make(map[string]C.Proxy),
|
||||||
observable: observable.NewObservable(logCh),
|
|
||||||
logCh: logCh,
|
|
||||||
configLock: &sync.RWMutex{},
|
configLock: &sync.RWMutex{},
|
||||||
|
traffic: C.NewTraffic(time.Second),
|
||||||
|
mode: Rule,
|
||||||
}
|
}
|
||||||
go tunnel.process()
|
|
||||||
go tunnel.subscribeLogs()
|
|
||||||
return tunnel
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetInstance() *Tunnel {
|
// Instance return singleton instance of Tunnel
|
||||||
|
func Instance() *Tunnel {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
tunnel = newTunnel()
|
tunnel = newTunnel()
|
||||||
|
go tunnel.process()
|
||||||
})
|
})
|
||||||
return tunnel
|
return tunnel
|
||||||
}
|
}
|
||||||
|
29
tunnel/util.go
Normal file
29
tunnel/util.go
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
package tunnel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TrafficTrack record traffic of net.Conn
|
||||||
|
type TrafficTrack struct {
|
||||||
|
net.Conn
|
||||||
|
traffic *C.Traffic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tt *TrafficTrack) Read(b []byte) (int, error) {
|
||||||
|
n, err := tt.Conn.Read(b)
|
||||||
|
tt.traffic.Down() <- int64(n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tt *TrafficTrack) Write(b []byte) (int, error) {
|
||||||
|
n, err := tt.Conn.Write(b)
|
||||||
|
tt.traffic.Up() <- int64(n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTrafficTrack(conn net.Conn, traffic *C.Traffic) *TrafficTrack {
|
||||||
|
return &TrafficTrack{traffic: traffic, Conn: conn}
|
||||||
|
}
|
@ -1,12 +0,0 @@
|
|||||||
package tunnel
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func trimArr(arr []string) (r []string) {
|
|
||||||
for _, e := range arr {
|
|
||||||
r = append(r, strings.Trim(e, " "))
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
Reference in New Issue
Block a user