Compare commits
38 Commits
Author | SHA1 | Date | |
---|---|---|---|
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 |
@ -1,15 +1,14 @@
|
||||
language: go
|
||||
sudo: false
|
||||
go:
|
||||
- "1.10"
|
||||
before_install:
|
||||
- go get -u github.com/golang/dep/cmd/dep
|
||||
- "1.11"
|
||||
install:
|
||||
- "$GOPATH/bin/dep ensure"
|
||||
- "go mod download"
|
||||
env:
|
||||
global:
|
||||
- NAME=clash
|
||||
- BINDIR=bin
|
||||
- GO111MODULE=on
|
||||
script:
|
||||
- go test ./...
|
||||
before_deploy: make -j releases
|
||||
|
@ -2,11 +2,9 @@ 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 && \
|
||||
cp /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /Country.mmdb
|
||||
RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh && \
|
||||
mkdir -p /go/src/github.com/Dreamacro/clash
|
||||
WORKDIR /go/src/github.com/Dreamacro/clash
|
||||
COPY . /go/src/github.com/Dreamacro/clash
|
||||
RUN dep ensure && \
|
||||
WORKDIR /clash-src
|
||||
COPY . /clash-src
|
||||
RUN go mod download && \
|
||||
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '-w -s' -o /clash && \
|
||||
chmod +x /clash
|
||||
|
||||
|
103
Gopkg.lock
generated
103
Gopkg.lock
generated
@ -1,103 +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/go-chi/chi"
|
||||
packages = ["."]
|
||||
revision = "e83ac2304db3c50cf03d96a2fcd39009d458bc35"
|
||||
version = "v3.3.2"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/go-chi/cors"
|
||||
packages = ["."]
|
||||
revision = "dba6525398619dead495962a916728e7ee2ca322"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/go-chi/render"
|
||||
packages = ["."]
|
||||
revision = "3215478343fbc559bd3fc08f7031bb134d6bdad5"
|
||||
version = "v1.0.1"
|
||||
|
||||
[[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",
|
||||
"internal/subtle",
|
||||
"poly1305",
|
||||
"ssh/terminal"
|
||||
]
|
||||
revision = "a2144134853fc9a27a7b1e3eb4f19f1a76df13c9"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/sys"
|
||||
packages = [
|
||||
"cpu",
|
||||
"unix",
|
||||
"windows"
|
||||
]
|
||||
revision = "ac767d655b305d4e9612f5f6e33120b9176c4ad4"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/eapache/channels.v1"
|
||||
packages = ["."]
|
||||
revision = "47238d5aae8c0fefd518ef2bee46290909cf8263"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/ini.v1"
|
||||
packages = ["."]
|
||||
revision = "358ee7663966325963d4e8b2e1fbd570c5195153"
|
||||
version = "v1.38.1"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "0ccb06b3617c87e75bd650f92adc99e55b93070e0b2a0bc71634270226e125fc"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
62
Gopkg.toml
62
Gopkg.toml
@ -1,62 +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/go-chi/chi"
|
||||
version = "3.3.2"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/go-chi/cors"
|
||||
version = "1.0.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/go-chi/render"
|
||||
version = "1.0.1"
|
||||
|
||||
[[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.38.1"
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
91
README.md
91
README.md
@ -25,6 +25,12 @@
|
||||
- HTTP/HTTPS and SOCKS proxy
|
||||
- Surge like configuration
|
||||
- GeoIP rule support
|
||||
- Support Vmess/Shadowsocks/Socks5
|
||||
- Support for Netfilter TCP redirect
|
||||
|
||||
## Discussion
|
||||
|
||||
[Telegram Group](https://t.me/clash_discuss)
|
||||
|
||||
## Install
|
||||
|
||||
@ -56,54 +62,89 @@ If you have Docker installed, you can run clash directly using `docker-compose`.
|
||||
|
||||
## 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:
|
||||
|
||||
```ini
|
||||
[General]
|
||||
port = 7890
|
||||
socks-port = 7891
|
||||
```yml
|
||||
# port of HTTP
|
||||
port: 7890
|
||||
|
||||
# port of SOCKS5
|
||||
socks-port: 7891
|
||||
|
||||
# redir proxy for Linux and macOS
|
||||
redir-port = 7892
|
||||
# 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
|
||||
log-level: info
|
||||
|
||||
# A RESTful API for clash
|
||||
external-controller = 127.0.0.1:8080
|
||||
external-controller: 127.0.0.1:9090
|
||||
|
||||
[Proxy]
|
||||
# name = ss, server, port, cipher, password
|
||||
# Secret for RESTful API (Optional)
|
||||
secret: ""
|
||||
|
||||
Proxy:
|
||||
|
||||
# shadowsocks
|
||||
# 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
|
||||
ss1 = ss, server1, port, AEAD_CHACHA20_POLY1305, password
|
||||
ss2 = ss, server2, 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 }
|
||||
|
||||
# name = socks5, server, port
|
||||
socks = socks5, server1, port
|
||||
# vmess
|
||||
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
||||
- { name: "vmess1", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto }
|
||||
- { name: "vmess2", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true }
|
||||
|
||||
[Proxy Group]
|
||||
# socks5
|
||||
- { name: "socks", type: socks5, server: server, port: 443 }
|
||||
|
||||
Proxy Group:
|
||||
# url-test select which proxy will be used by benchmarking speed to a URL.
|
||||
# name = url-test, [proxies], url, interval(second)
|
||||
auto = url-test, ss1, ss2, http://www.google.com/generate_204, 300
|
||||
- { name: "auto", type: url-test, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
|
||||
|
||||
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
||||
- { 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 = select, [proxies]
|
||||
Proxy = select, ss1, ss2, auto
|
||||
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
|
||||
|
||||
[Rule]
|
||||
DOMAIN-SUFFIX,google.com,Proxy
|
||||
DOMAIN-KEYWORD,google,Proxy
|
||||
DOMAIN-SUFFIX,ad.com,REJECT
|
||||
GEOIP,CN,DIRECT
|
||||
FINAL,,Proxy # note: there is two ","
|
||||
Rule:
|
||||
- DOMAIN-SUFFIX,google.com,Proxy
|
||||
- DOMAIN-KEYWORD,google,Proxy
|
||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
||||
- GEOIP,CN,DIRECT
|
||||
# note: there is two ","
|
||||
- FINAL,,Proxy
|
||||
```
|
||||
|
||||
## Thanks
|
||||
|
||||
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||
|
||||
[google/tcpproxy](https://github.com/google/tcpproxy)
|
||||
[v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||
|
||||
## License
|
||||
|
||||
|
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,
|
||||
}
|
||||
}
|
37
adapters/inbound/socket.go
Normal file
37
adapters/inbound/socket.go
Normal file
@ -0,0 +1,37 @@
|
||||
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) *SocketAdapter {
|
||||
return &SocketAdapter{
|
||||
conn: conn,
|
||||
metadata: parseSocksAddr(target),
|
||||
}
|
||||
}
|
71
adapters/inbound/util.go
Normal file
71
adapters/inbound/util.go
Normal file
@ -0,0 +1,71 @@
|
||||
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 {
|
||||
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.Metadata{
|
||||
NetWork: C.TCP,
|
||||
AddrType: int(target[0]),
|
||||
Host: host,
|
||||
IP: &ip,
|
||||
Port: port,
|
||||
}
|
||||
}
|
||||
|
||||
func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||
host := request.URL.Hostname()
|
||||
port := request.URL.Port()
|
||||
if port == "" {
|
||||
port = "80"
|
||||
}
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
var resolveIP *net.IP
|
||||
if err == nil {
|
||||
resolveIP = &ipAddr.IP
|
||||
}
|
||||
|
||||
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.Metadata{
|
||||
NetWork: C.TCP,
|
||||
AddrType: addType,
|
||||
Host: host,
|
||||
IP: resolveIP,
|
||||
Port: port,
|
||||
}
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
// PeekedConn handle http connection and buffed HTTP data
|
||||
type PeekedConn struct {
|
||||
net.Conn
|
||||
Peeked []byte
|
||||
host string
|
||||
isHTTP bool
|
||||
}
|
||||
|
||||
func (c *PeekedConn) Read(p []byte) (n int, err error) {
|
||||
if len(c.Peeked) > 0 {
|
||||
n = copy(p, c.Peeked)
|
||||
c.Peeked = c.Peeked[n:]
|
||||
if len(c.Peeked) == 0 {
|
||||
c.Peeked = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Sometimes firefox just open a socket to process multiple domains in HTTP
|
||||
// The temporary solution is to return io.EOF when encountering different HOST
|
||||
if c.isHTTP {
|
||||
br := bufio.NewReader(bytes.NewReader(p))
|
||||
_, hostName := ParserHTTPHostHeader(br)
|
||||
if hostName != "" {
|
||||
if !strings.Contains(hostName, ":") {
|
||||
hostName += ":80"
|
||||
}
|
||||
|
||||
if hostName != c.host {
|
||||
return 0, io.EOF
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
|
||||
// HTTPAdapter is a adapter for HTTP connection
|
||||
type HTTPAdapter struct {
|
||||
addr *C.Addr
|
||||
conn *PeekedConn
|
||||
}
|
||||
|
||||
// Close HTTP connection
|
||||
func (h *HTTPAdapter) Close() {
|
||||
h.conn.Close()
|
||||
}
|
||||
|
||||
// Addr return destination address
|
||||
func (h *HTTPAdapter) Addr() *C.Addr {
|
||||
return h.addr
|
||||
}
|
||||
|
||||
// Conn return raw net.Conn of HTTP
|
||||
func (h *HTTPAdapter) Conn() net.Conn {
|
||||
return h.conn
|
||||
}
|
||||
|
||||
// NewHTTP is HTTPAdapter generator
|
||||
func NewHTTP(host string, peeked []byte, isHTTP bool, conn net.Conn) *HTTPAdapter {
|
||||
return &HTTPAdapter{
|
||||
addr: parseHTTPAddr(host),
|
||||
conn: &PeekedConn{
|
||||
Peeked: peeked,
|
||||
Conn: conn,
|
||||
host: host,
|
||||
isHTTP: isHTTP,
|
||||
},
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
// SocksAdapter is a adapter for socks and redir connection
|
||||
type SocksAdapter struct {
|
||||
conn net.Conn
|
||||
addr *C.Addr
|
||||
}
|
||||
|
||||
// Close socks and redir connection
|
||||
func (s *SocksAdapter) Close() {
|
||||
s.conn.Close()
|
||||
}
|
||||
|
||||
// Addr return destination address
|
||||
func (s *SocksAdapter) Addr() *C.Addr {
|
||||
return s.addr
|
||||
}
|
||||
|
||||
// Conn return raw net.Conn
|
||||
func (s *SocksAdapter) Conn() net.Conn {
|
||||
return s.conn
|
||||
}
|
||||
|
||||
// NewSocks is SocksAdapter generator
|
||||
func NewSocks(target socks.Addr, conn net.Conn) *SocksAdapter {
|
||||
return &SocksAdapter{
|
||||
conn: conn,
|
||||
addr: parseSocksAddr(target),
|
||||
}
|
||||
}
|
@ -1,140 +0,0 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
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 parseHTTPAddr(target string) *C.Addr {
|
||||
host, port, _ := net.SplitHostPort(target)
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
var resolveIP *net.IP
|
||||
if err == nil {
|
||||
resolveIP = &ipAddr.IP
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
// ParserHTTPHostHeader returns the HTTP Host header from br without
|
||||
// consuming any of its bytes. It returns "" if it can't find one.
|
||||
func ParserHTTPHostHeader(br *bufio.Reader) (method, host string) {
|
||||
// br := bufio.NewReader(bytes.NewReader(data))
|
||||
const maxPeek = 4 << 10
|
||||
peekSize := 0
|
||||
for {
|
||||
peekSize++
|
||||
if peekSize > maxPeek {
|
||||
b, _ := br.Peek(br.Buffered())
|
||||
return method, httpHostHeaderFromBytes(b)
|
||||
}
|
||||
b, err := br.Peek(peekSize)
|
||||
if n := br.Buffered(); n > peekSize {
|
||||
b, _ = br.Peek(n)
|
||||
peekSize = n
|
||||
}
|
||||
if len(b) > 0 {
|
||||
if b[0] < 'A' || b[0] > 'Z' {
|
||||
// Doesn't look like an HTTP verb
|
||||
// (GET, POST, etc).
|
||||
return
|
||||
}
|
||||
if bytes.Index(b, crlfcrlf) != -1 || bytes.Index(b, lflf) != -1 {
|
||||
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(b)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if len(req.Header["Host"]) > 1 {
|
||||
// TODO(bradfitz): what does
|
||||
// ReadRequest do if there are
|
||||
// multiple Host headers?
|
||||
return
|
||||
}
|
||||
return req.Method, req.Host
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return method, httpHostHeaderFromBytes(b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
lfHostColon = []byte("\nHost:")
|
||||
lfhostColon = []byte("\nhost:")
|
||||
crlf = []byte("\r\n")
|
||||
lf = []byte("\n")
|
||||
crlfcrlf = []byte("\r\n\r\n")
|
||||
lflf = []byte("\n\n")
|
||||
)
|
||||
|
||||
func httpHostHeaderFromBytes(b []byte) string {
|
||||
if i := bytes.Index(b, lfHostColon); i != -1 {
|
||||
return string(bytes.TrimSpace(untilEOL(b[i+len(lfHostColon):])))
|
||||
}
|
||||
if i := bytes.Index(b, lfhostColon); i != -1 {
|
||||
return string(bytes.TrimSpace(untilEOL(b[i+len(lfhostColon):])))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// untilEOL returns v, truncated before the first '\n' byte, if any.
|
||||
// The returned slice may include a '\r' at the end.
|
||||
func untilEOL(v []byte) []byte {
|
||||
if i := bytes.IndexByte(v, '\n'); i != -1 {
|
||||
return v[:i]
|
||||
}
|
||||
return v
|
||||
}
|
@ -24,19 +24,19 @@ func (d *DirectAdapter) Conn() net.Conn {
|
||||
type Direct struct{}
|
||||
|
||||
func (d *Direct) Name() string {
|
||||
return "Direct"
|
||||
return "DIRECT"
|
||||
}
|
||||
|
||||
func (d *Direct) Type() C.AdapterType {
|
||||
return C.Direct
|
||||
}
|
||||
|
||||
func (d *Direct) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
||||
c, err := net.Dial("tcp", net.JoinHostPort(addr.String(), addr.Port))
|
||||
func (d *Direct) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
c, err := net.Dial("tcp", net.JoinHostPort(metadata.String(), metadata.Port))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.(*net.TCPConn).SetKeepAlive(true)
|
||||
tcpKeepAlive(c)
|
||||
return &DirectAdapter{conn: c}, nil
|
||||
}
|
||||
|
136
adapters/outbound/fallback.go
Normal file
136
adapters/outbound/fallback.go
Normal file
@ -0,0 +1,136 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type proxy struct {
|
||||
RawProxy C.Proxy
|
||||
Valid bool
|
||||
}
|
||||
|
||||
type Fallback struct {
|
||||
name string
|
||||
proxies []*proxy
|
||||
rawURL string
|
||||
interval time.Duration
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type FallbackOption struct {
|
||||
Name string `proxy:"name"`
|
||||
Proxies []string `proxy:"proxies"`
|
||||
URL string `proxy:"url"`
|
||||
Interval int `proxy:"interval"`
|
||||
}
|
||||
|
||||
func (f *Fallback) Name() string {
|
||||
return f.name
|
||||
}
|
||||
|
||||
func (f *Fallback) Type() C.AdapterType {
|
||||
return C.Fallback
|
||||
}
|
||||
|
||||
func (f *Fallback) Now() string {
|
||||
_, proxy := f.findNextValidProxy(0)
|
||||
if proxy != nil {
|
||||
return proxy.RawProxy.Name()
|
||||
}
|
||||
return f.proxies[0].RawProxy.Name()
|
||||
}
|
||||
|
||||
func (f *Fallback) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
idx := 0
|
||||
var proxy *proxy
|
||||
for {
|
||||
idx, proxy = f.findNextValidProxy(idx)
|
||||
if proxy == nil {
|
||||
break
|
||||
}
|
||||
adapter, err = proxy.RawProxy.Generator(metadata)
|
||||
if err != nil {
|
||||
proxy.Valid = false
|
||||
idx++
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
return f.proxies[0].RawProxy.Generator(metadata)
|
||||
}
|
||||
|
||||
func (f *Fallback) Close() {
|
||||
f.done <- struct{}{}
|
||||
}
|
||||
|
||||
func (f *Fallback) loop() {
|
||||
tick := time.NewTicker(f.interval)
|
||||
go f.validTest()
|
||||
Loop:
|
||||
for {
|
||||
select {
|
||||
case <-tick.C:
|
||||
go f.validTest()
|
||||
case <-f.done:
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Fallback) findNextValidProxy(start int) (int, *proxy) {
|
||||
for i := start; i < len(f.proxies); i++ {
|
||||
if f.proxies[i].Valid {
|
||||
return i, f.proxies[i]
|
||||
}
|
||||
}
|
||||
return -1, nil
|
||||
}
|
||||
|
||||
func (f *Fallback) validTest() {
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(f.proxies))
|
||||
|
||||
for _, p := range f.proxies {
|
||||
go func(p *proxy) {
|
||||
_, err := DelayTest(p.RawProxy, f.rawURL)
|
||||
p.Valid = err == nil
|
||||
wg.Done()
|
||||
}(p)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
||||
_, err := urlToMetadata(option.URL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(proxies) < 1 {
|
||||
return nil, errors.New("The number of proxies cannot be 0")
|
||||
}
|
||||
|
||||
interval := time.Duration(option.Interval) * time.Second
|
||||
warpperProxies := make([]*proxy, len(proxies))
|
||||
for idx := range proxies {
|
||||
warpperProxies[idx] = &proxy{
|
||||
RawProxy: proxies[idx],
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
|
||||
Fallback := &Fallback{
|
||||
name: option.Name,
|
||||
proxies: warpperProxies,
|
||||
rawURL: option.URL,
|
||||
interval: interval,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go Fallback.loop()
|
||||
return Fallback, nil
|
||||
}
|
@ -25,14 +25,14 @@ type Reject struct {
|
||||
}
|
||||
|
||||
func (r *Reject) Name() string {
|
||||
return "Reject"
|
||||
return "REJECT"
|
||||
}
|
||||
|
||||
func (r *Reject) Type() C.AdapterType {
|
||||
return C.Reject
|
||||
}
|
||||
|
||||
func (r *Reject) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
||||
func (r *Reject) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
return &RejectAdapter{conn: &NopConn{}}, nil
|
||||
}
|
||||
|
@ -13,6 +13,11 @@ type Selector struct {
|
||||
proxies map[string]C.Proxy
|
||||
}
|
||||
|
||||
type SelectorOption struct {
|
||||
Name string `proxy:"name"`
|
||||
Proxies []string `proxy:"proxies"`
|
||||
}
|
||||
|
||||
func (s *Selector) Name() string {
|
||||
return s.name
|
||||
}
|
||||
@ -21,8 +26,8 @@ func (s *Selector) Type() C.AdapterType {
|
||||
return C.Selector
|
||||
}
|
||||
|
||||
func (s *Selector) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
||||
return s.selected.Generator(addr)
|
||||
func (s *Selector) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
return s.selected.Generator(metadata)
|
||||
}
|
||||
|
||||
func (s *Selector) Now() string {
|
||||
@ -47,21 +52,20 @@ func (s *Selector) Set(name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewSelector(name string, proxies map[string]C.Proxy) (*Selector, error) {
|
||||
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)
|
||||
var init string
|
||||
for k, v := range proxies {
|
||||
mapping[k] = v
|
||||
init = k
|
||||
for _, proxy := range proxies {
|
||||
mapping[proxy.Name()] = proxy
|
||||
}
|
||||
|
||||
s := &Selector{
|
||||
name: name,
|
||||
proxies: mapping,
|
||||
selected: proxies[init],
|
||||
selected: proxies[0],
|
||||
}
|
||||
return s, nil
|
||||
}
|
116
adapters/outbound/shadowsocks.go
Normal file
116
adapters/outbound/shadowsocks.go
Normal file
@ -0,0 +1,116 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"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.Dial("tcp", ss.server)
|
||||
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 NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
server := fmt.Sprintf("%s:%d", option.Server, 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)
|
||||
}
|
@ -9,7 +9,7 @@ import (
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
// Socks5Adapter is a shadowsocks adapter
|
||||
@ -31,6 +31,12 @@ type Socks5 struct {
|
||||
name string
|
||||
}
|
||||
|
||||
type Socks5Option struct {
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
}
|
||||
|
||||
func (ss *Socks5) Name() string {
|
||||
return ss.name
|
||||
}
|
||||
@ -39,20 +45,19 @@ func (ss *Socks5) Type() C.AdapterType {
|
||||
return C.Socks5
|
||||
}
|
||||
|
||||
func (ss *Socks5) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
||||
func (ss *Socks5) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
c, err := net.Dial("tcp", ss.addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error", ss.addr)
|
||||
}
|
||||
c.(*net.TCPConn).SetKeepAlive(true)
|
||||
|
||||
if err := ss.sharkHand(addr, c); err != nil {
|
||||
tcpKeepAlive(c)
|
||||
if err := ss.shakeHand(metadata, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Socks5Adapter{conn: c}, nil
|
||||
}
|
||||
|
||||
func (ss *Socks5) sharkHand(addr *C.Addr, rw io.ReadWriter) error {
|
||||
func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||
buf := make([]byte, socks.MaxAddrLen)
|
||||
|
||||
// VER, CMD, RSV
|
||||
@ -72,7 +77,7 @@ func (ss *Socks5) sharkHand(addr *C.Addr, rw io.ReadWriter) error {
|
||||
}
|
||||
|
||||
// VER, CMD, RSV, ADDR
|
||||
if _, err := rw.Write(bytes.Join([][]byte{[]byte{5, 1, 0}, serializesSocksAddr(addr)}, []byte(""))); err != nil {
|
||||
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -83,9 +88,9 @@ func (ss *Socks5) sharkHand(addr *C.Addr, rw io.ReadWriter) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewSocks5(name, addr string) *Socks5 {
|
||||
func NewSocks5(option Socks5Option) *Socks5 {
|
||||
return &Socks5{
|
||||
addr: addr,
|
||||
name: name,
|
||||
addr: fmt.Sprintf("%s:%d", option.Server, option.Port),
|
||||
name: option.Name,
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@ -8,12 +9,19 @@ import (
|
||||
)
|
||||
|
||||
type URLTest struct {
|
||||
name string
|
||||
proxies []C.Proxy
|
||||
rawURL string
|
||||
fast C.Proxy
|
||||
delay time.Duration
|
||||
done chan struct{}
|
||||
name string
|
||||
proxies []C.Proxy
|
||||
rawURL string
|
||||
fast C.Proxy
|
||||
interval time.Duration
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type URLTestOption struct {
|
||||
Name string `proxy:"name"`
|
||||
Proxies []string `proxy:"proxies"`
|
||||
URL string `proxy:"url"`
|
||||
Interval int `proxy:"interval"`
|
||||
}
|
||||
|
||||
func (u *URLTest) Name() string {
|
||||
@ -28,8 +36,8 @@ func (u *URLTest) Now() string {
|
||||
return u.fast.Name()
|
||||
}
|
||||
|
||||
func (u *URLTest) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
||||
return u.fast.Generator(addr)
|
||||
func (u *URLTest) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
return u.fast.Generator(metadata)
|
||||
}
|
||||
|
||||
func (u *URLTest) Close() {
|
||||
@ -37,7 +45,7 @@ func (u *URLTest) Close() {
|
||||
}
|
||||
|
||||
func (u *URLTest) loop() {
|
||||
tick := time.NewTicker(u.delay)
|
||||
tick := time.NewTicker(u.interval)
|
||||
go u.speedTest()
|
||||
Loop:
|
||||
for {
|
||||
@ -55,7 +63,7 @@ func (u *URLTest) speedTest() {
|
||||
wg.Add(len(u.proxies))
|
||||
c := make(chan interface{})
|
||||
fast := selectFast(c)
|
||||
timer := time.NewTimer(u.delay)
|
||||
timer := time.NewTimer(u.interval)
|
||||
|
||||
for _, p := range u.proxies {
|
||||
go func(p C.Proxy) {
|
||||
@ -83,19 +91,23 @@ func (u *URLTest) speedTest() {
|
||||
}
|
||||
}
|
||||
|
||||
func NewURLTest(name string, proxies []C.Proxy, rawURL string, delay time.Duration) (*URLTest, error) {
|
||||
_, err := urlToAddr(rawURL)
|
||||
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: name,
|
||||
proxies: proxies[:],
|
||||
rawURL: rawURL,
|
||||
fast: proxies[0],
|
||||
delay: delay,
|
||||
done: make(chan struct{}),
|
||||
name: option.Name,
|
||||
proxies: proxies[:],
|
||||
rawURL: option.URL,
|
||||
fast: proxies[0],
|
||||
interval: interval,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go urlTest.loop()
|
||||
return urlTest, nil
|
@ -12,7 +12,7 @@ import (
|
||||
|
||||
// DelayTest get the delay for the specified URL
|
||||
func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
|
||||
addr, err := urlToAddr(url)
|
||||
addr, err := urlToMetadata(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@ -34,16 +34,16 @@ func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
client := http.Client{Transport: transport}
|
||||
req, err := client.Get(url)
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Body.Close()
|
||||
resp.Body.Close()
|
||||
t = int16(time.Since(start) / time.Millisecond)
|
||||
return
|
||||
}
|
||||
|
||||
func urlToAddr(rawURL string) (addr C.Addr, err error) {
|
||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return
|
||||
@ -61,7 +61,7 @@ func urlToAddr(rawURL string) (addr C.Addr, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
addr = C.Addr{
|
||||
addr = C.Metadata{
|
||||
AddrType: C.AtypDomainName,
|
||||
Host: u.Hostname(),
|
||||
IP: nil,
|
||||
@ -84,3 +84,10 @@ func selectFast(in chan interface{}) chan interface{} {
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func tcpKeepAlive(c net.Conn) {
|
||||
if tcp, ok := c.(*net.TCPConn); ok {
|
||||
tcp.SetKeepAlive(true)
|
||||
tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||
}
|
||||
}
|
105
adapters/outbound/vmess.go
Normal file
105
adapters/outbound/vmess.go
Normal file
@ -0,0 +1,105 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"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"`
|
||||
}
|
||||
|
||||
func (ss *Vmess) Name() string {
|
||||
return ss.name
|
||||
}
|
||||
|
||||
func (ss *Vmess) Type() C.AdapterType {
|
||||
return C.Vmess
|
||||
}
|
||||
|
||||
func (ss *Vmess) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
||||
c, err := net.Dial("tcp", ss.server)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error", ss.server)
|
||||
}
|
||||
tcpKeepAlive(c)
|
||||
c = ss.client.New(c, parseVmessAddr(metadata))
|
||||
return &VmessAdapter{conn: c}, err
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Vmess{
|
||||
name: option.Name,
|
||||
server: fmt.Sprintf("%s:%d", option.Server, 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,101 +0,0 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"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
|
||||
}
|
||||
|
||||
// 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
|
||||
cipher core.Cipher
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) Name() string {
|
||||
return ss.name
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) Type() C.AdapterType {
|
||||
return C.Shadowsocks
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
|
||||
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 = ss.cipher.StreamConn(c)
|
||||
_, err = c.Write(serializesSocksAddr(addr))
|
||||
return &ShadowsocksAdapter{conn: c}, err
|
||||
}
|
||||
|
||||
func NewShadowSocks(name string, ssURL string) (*ShadowSocks, error) {
|
||||
var key []byte
|
||||
server, cipher, password, _ := parseURL(ssURL)
|
||||
ciph, err := core.PickCipher(cipher, key, password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
||||
}
|
||||
return &ShadowSocks{
|
||||
server: server,
|
||||
name: name,
|
||||
cipher: ciph,
|
||||
}, nil
|
||||
}
|
||||
|
||||
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{{aType, len}, host, port}
|
||||
case socks.AtypIPv4:
|
||||
host := addr.IP.To4()
|
||||
buf = [][]byte{{aType}, host, port}
|
||||
case socks.AtypIPv6:
|
||||
host := addr.IP.To16()
|
||||
buf = [][]byte{{aType}, host, port}
|
||||
}
|
||||
return bytes.Join(buf, []byte(""))
|
||||
}
|
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,
|
||||
}
|
||||
}
|
190
component/simple-obfs/tls.go
Normal file
190
component/simple-obfs/tls.go
Normal file
@ -0,0 +1,190 @@
|
||||
package obfs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().Unix())
|
||||
}
|
||||
|
||||
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) {
|
||||
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, 32)
|
||||
sessionID := make([]byte, 32)
|
||||
size := make([]byte, 2)
|
||||
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)
|
||||
binary.BigEndian.PutUint16(size, uint16(208+len(data)+len(server)))
|
||||
buf.WriteByte(0)
|
||||
buf.Write(size)
|
||||
buf.Write([]byte{0x03, 0x03})
|
||||
|
||||
// random, sid len, sid
|
||||
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.BigEndian.PutUint16(size, uint16(79+len(data)+len(server)))
|
||||
buf.Write(size)
|
||||
|
||||
// session ticket
|
||||
buf.Write([]byte{0x00, 0x23})
|
||||
binary.BigEndian.PutUint16(size, uint16(len(data)))
|
||||
buf.Write(size)
|
||||
buf.Write(data)
|
||||
|
||||
// server name
|
||||
buf.Write([]byte{0x00, 0x00})
|
||||
binary.BigEndian.PutUint16(size, uint16(len(server)+5))
|
||||
buf.Write(size)
|
||||
binary.BigEndian.PutUint16(size, uint16(len(server)+3))
|
||||
buf.Write(size)
|
||||
buf.WriteByte(0)
|
||||
binary.BigEndian.PutUint16(size, uint16(len(server)))
|
||||
buf.Write(size)
|
||||
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
|
||||
}
|
213
component/vmess/conn.go
Normal file
213
component/vmess/conn.go
Normal file
@ -0,0 +1,213 @@
|
||||
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 := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(timestamp, uint64(time.Now().UTC().Unix()))
|
||||
|
||||
h := hmac.New(md5.New, vc.id.UUID.Bytes())
|
||||
h.Write(timestamp)
|
||||
_, 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(time.Now().UTC()))
|
||||
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.UTC().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,
|
||||
}
|
||||
}
|
54
component/vmess/user.go
Normal file
54
component/vmess/user.go
Normal file
@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
return alterIDs
|
||||
}
|
117
component/vmess/vmess.go
Normal file
117
component/vmess/vmess.go
Normal file
@ -0,0 +1,117 @@
|
||||
package vmess
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"runtime"
|
||||
|
||||
"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 tlsConfig = &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Config of vmess
|
||||
type Config struct {
|
||||
UUID string
|
||||
AlterID uint16
|
||||
Security string
|
||||
TLS bool
|
||||
}
|
||||
|
||||
// New return a Conn with net.Conn and DstAddr
|
||||
func (c *Client) New(conn net.Conn, dst *DstAddr) net.Conn {
|
||||
r := rand.Intn(len(c.user))
|
||||
if c.tls {
|
||||
conn = tls.Client(conn, tlsConfig)
|
||||
}
|
||||
return newConn(conn, c.user[r], dst, c.security)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
return &Client{
|
||||
user: newAlterIDs(newID(&uid), config.AlterID),
|
||||
uuid: &uid,
|
||||
security: security,
|
||||
tls: config.TLS,
|
||||
}, nil
|
||||
}
|
305
config/config.go
305
config/config.go
@ -2,19 +2,20 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/remote"
|
||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||
"github.com/Dreamacro/clash/common/observable"
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/observable"
|
||||
R "github.com/Dreamacro/clash/rules"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/ini.v1"
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -40,6 +41,22 @@ type ProxyConfig struct {
|
||||
AllowLan *bool
|
||||
}
|
||||
|
||||
// RawConfig is raw config struct
|
||||
type RawConfig struct {
|
||||
Port int `yaml:"port"`
|
||||
SocksPort int `yaml:"socks-port"`
|
||||
RedirPort int `yaml:"redir-port"`
|
||||
AllowLan bool `yaml:"allow-lan"`
|
||||
Mode string `yaml:"mode"`
|
||||
LogLevel string `yaml:"log-level"`
|
||||
ExternalController string `yaml:"external-controller"`
|
||||
Secret string `yaml:"secret"`
|
||||
|
||||
Proxy []map[string]interface{} `yaml:"Proxy"`
|
||||
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
||||
Rule []string `yaml:"Rule"`
|
||||
}
|
||||
|
||||
// Config is clash config manager
|
||||
type Config struct {
|
||||
general *General
|
||||
@ -69,14 +86,30 @@ func (c *Config) Report() chan<- interface{} {
|
||||
return c.reportCh
|
||||
}
|
||||
|
||||
func (c *Config) readConfig() (*ini.File, error) {
|
||||
if _, err := os.Stat(C.ConfigPath); os.IsNotExist(err) {
|
||||
func (c *Config) readConfig() (*RawConfig, error) {
|
||||
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
return ini.LoadSources(
|
||||
ini.LoadOptions{AllowBooleanKeys: true},
|
||||
C.ConfigPath,
|
||||
)
|
||||
data, err := ioutil.ReadFile(C.Path.Config())
|
||||
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: Rule.String(),
|
||||
LogLevel: C.INFO.String(),
|
||||
Rule: []string{},
|
||||
Proxy: []map[string]interface{}{},
|
||||
ProxyGroup: []map[string]interface{}{},
|
||||
}
|
||||
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
||||
return rawConfig, err
|
||||
}
|
||||
|
||||
// Parse config
|
||||
@ -134,15 +167,13 @@ func (c *Config) UpdateRules() error {
|
||||
return c.parseRules(cfg)
|
||||
}
|
||||
|
||||
func (c *Config) parseGeneral(cfg *ini.File) error {
|
||||
general := cfg.Section("General")
|
||||
|
||||
port := general.Key("port").RangeInt(0, 1, 65535)
|
||||
socksPort := general.Key("socks-port").RangeInt(0, 1, 65535)
|
||||
redirPort := general.Key("redir-port").RangeInt(0, 1, 65535)
|
||||
allowLan := general.Key("allow-lan").MustBool()
|
||||
logLevelString := general.Key("log-level").MustString(C.INFO.String())
|
||||
modeString := general.Key("mode").MustString(Rule.String())
|
||||
func (c *Config) parseGeneral(cfg *RawConfig) error {
|
||||
port := cfg.Port
|
||||
socksPort := cfg.SocksPort
|
||||
redirPort := cfg.RedirPort
|
||||
allowLan := cfg.AllowLan
|
||||
logLevelString := cfg.LogLevel
|
||||
modeString := cfg.Mode
|
||||
|
||||
mode, exist := ModeMapping[modeString]
|
||||
if !exist {
|
||||
@ -163,8 +194,9 @@ func (c *Config) parseGeneral(cfg *ini.File) error {
|
||||
LogLevel: logLevel,
|
||||
}
|
||||
|
||||
if restAddr := general.Key("external-controller").String(); restAddr != "" {
|
||||
if restAddr := cfg.ExternalController; restAddr != "" {
|
||||
c.event <- &Event{Type: "external-controller", Payload: restAddr}
|
||||
c.event <- &Event{Type: "secret", Payload: cfg.Secret}
|
||||
}
|
||||
|
||||
c.UpdateGeneral(*c.general)
|
||||
@ -189,123 +221,168 @@ func (c *Config) UpdateProxy(pc ProxyConfig) {
|
||||
c.general.AllowLan = *pc.AllowLan
|
||||
}
|
||||
|
||||
if (pc.AllowLan != nil || pc.Port != nil) && *pc.Port != 0 {
|
||||
c.general.Port = *pc.Port
|
||||
c.event <- &Event{Type: "http-addr", Payload: genAddr(*pc.Port, c.general.AllowLan)}
|
||||
c.general.Port = *or(pc.Port, &c.general.Port)
|
||||
if c.general.Port != 0 && (pc.AllowLan != nil || pc.Port != nil) {
|
||||
c.event <- &Event{Type: "http-addr", Payload: genAddr(c.general.Port, c.general.AllowLan)}
|
||||
}
|
||||
|
||||
if (pc.AllowLan != nil || pc.SocksPort != nil) && *pc.SocksPort != 0 {
|
||||
c.general.SocksPort = *pc.SocksPort
|
||||
c.event <- &Event{Type: "socks-addr", Payload: genAddr(*pc.SocksPort, c.general.AllowLan)}
|
||||
c.general.SocksPort = *or(pc.SocksPort, &c.general.SocksPort)
|
||||
if c.general.SocksPort != 0 && (pc.AllowLan != nil || pc.SocksPort != nil) {
|
||||
c.event <- &Event{Type: "socks-addr", Payload: genAddr(c.general.SocksPort, c.general.AllowLan)}
|
||||
}
|
||||
|
||||
if (pc.AllowLan != nil || pc.RedirPort != nil) && *pc.RedirPort != 0 {
|
||||
c.general.RedirPort = *pc.RedirPort
|
||||
c.event <- &Event{Type: "redir-addr", Payload: genAddr(*pc.RedirPort, c.general.AllowLan)}
|
||||
c.general.RedirPort = *or(pc.RedirPort, &c.general.RedirPort)
|
||||
if c.general.RedirPort != 0 && (pc.AllowLan != nil || pc.RedirPort != nil) {
|
||||
c.event <- &Event{Type: "redir-addr", Payload: genAddr(c.general.RedirPort, c.general.AllowLan)}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) parseProxies(cfg *ini.File) error {
|
||||
func (c *Config) parseProxies(cfg *RawConfig) error {
|
||||
proxies := make(map[string]C.Proxy)
|
||||
proxiesConfig := cfg.Section("Proxy")
|
||||
groupsConfig := cfg.Section("Proxy Group")
|
||||
proxiesConfig := cfg.Proxy
|
||||
groupsConfig := cfg.ProxyGroup
|
||||
|
||||
// parse proxy
|
||||
for _, key := range proxiesConfig.Keys() {
|
||||
proxy := key.Strings(",")
|
||||
if len(proxy) == 0 {
|
||||
continue
|
||||
}
|
||||
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])
|
||||
ss, err := adapters.NewShadowSocks(key.Name(), ssURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
proxies[key.Name()] = ss
|
||||
// socks5, server, port
|
||||
case "socks5":
|
||||
if len(proxy) < 3 {
|
||||
continue
|
||||
}
|
||||
addr := fmt.Sprintf("%s:%s", proxy[1], proxy[2])
|
||||
socks5 := adapters.NewSocks5(key.Name(), addr)
|
||||
proxies[key.Name()] = socks5
|
||||
}
|
||||
}
|
||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||
|
||||
// parse proxy group
|
||||
for _, key := range groupsConfig.Keys() {
|
||||
rule := strings.Split(key.Value(), ",")
|
||||
rule = trimArr(rule)
|
||||
switch rule[0] {
|
||||
case "url-test":
|
||||
if len(rule) < 4 {
|
||||
return fmt.Errorf("URLTest need more than 4 param")
|
||||
}
|
||||
proxyNames := rule[1 : len(rule)-2]
|
||||
delay, _ := strconv.Atoi(rule[len(rule)-1])
|
||||
url := rule[len(rule)-2]
|
||||
var ps []C.Proxy
|
||||
for _, name := range proxyNames {
|
||||
if p, ok := proxies[name]; ok {
|
||||
ps = append(ps, p)
|
||||
}
|
||||
}
|
||||
|
||||
adapter, err := adapters.NewURLTest(key.Name(), ps, url, time.Duration(delay)*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Config error: %s", err.Error())
|
||||
}
|
||||
proxies[key.Name()] = adapter
|
||||
case "select":
|
||||
if len(rule) < 2 {
|
||||
return fmt.Errorf("Selector need more than 2 param")
|
||||
}
|
||||
proxyNames := rule[1:]
|
||||
selectProxy := make(map[string]C.Proxy)
|
||||
for _, name := range proxyNames {
|
||||
proxy, exist := proxies[name]
|
||||
if !exist {
|
||||
return fmt.Errorf("Proxy %s not exist", name)
|
||||
}
|
||||
selectProxy[name] = proxy
|
||||
}
|
||||
selector, err := adapters.NewSelector(key.Name(), selectProxy)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Selector create error: %s", err.Error())
|
||||
}
|
||||
proxies[key.Name()] = selector
|
||||
}
|
||||
}
|
||||
|
||||
// init proxy
|
||||
proxies["GLOBAL"], _ = adapters.NewSelector("GLOBAL", proxies)
|
||||
proxies["DIRECT"] = adapters.NewDirect()
|
||||
proxies["REJECT"] = adapters.NewReject()
|
||||
|
||||
// parse proxy
|
||||
for idx, mapping := range proxiesConfig {
|
||||
proxyType, existType := mapping["type"].(string)
|
||||
proxyName, existName := mapping["name"].(string)
|
||||
if !existType && existName {
|
||||
return fmt.Errorf("Proxy %d missing type or name", idx)
|
||||
}
|
||||
|
||||
if _, exist := proxies[proxyName]; exist {
|
||||
return fmt.Errorf("Proxy %s is the duplicate name", proxyName)
|
||||
}
|
||||
var proxy C.Proxy
|
||||
var err error
|
||||
switch proxyType {
|
||||
case "ss":
|
||||
ssOption := &adapters.ShadowSocksOption{}
|
||||
err = decoder.Decode(mapping, ssOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy, err = adapters.NewShadowSocks(*ssOption)
|
||||
case "socks5":
|
||||
socksOption := &adapters.Socks5Option{}
|
||||
err = decoder.Decode(mapping, socksOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy = adapters.NewSocks5(*socksOption)
|
||||
case "vmess":
|
||||
vmessOption := &adapters.VmessOption{}
|
||||
err = decoder.Decode(mapping, vmessOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
proxy, err = adapters.NewVmess(*vmessOption)
|
||||
default:
|
||||
return fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("Proxy %s: %s", proxyName, err.Error())
|
||||
}
|
||||
proxies[proxyName] = proxy
|
||||
}
|
||||
|
||||
// parse proxy group
|
||||
for idx, mapping := range groupsConfig {
|
||||
groupType, existType := mapping["type"].(string)
|
||||
groupName, existName := mapping["name"].(string)
|
||||
if !existType && existName {
|
||||
return fmt.Errorf("ProxyGroup %d: missing type or name", idx)
|
||||
}
|
||||
|
||||
if _, exist := proxies[groupName]; exist {
|
||||
return fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
||||
}
|
||||
var group C.Proxy
|
||||
var err error
|
||||
switch groupType {
|
||||
case "url-test":
|
||||
urlTestOption := &adapters.URLTestOption{}
|
||||
err = decoder.Decode(mapping, urlTestOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
ps, err := getProxies(proxies, urlTestOption.Proxies)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||
}
|
||||
group, err = adapters.NewURLTest(*urlTestOption, ps)
|
||||
case "select":
|
||||
selectorOption := &adapters.SelectorOption{}
|
||||
err = decoder.Decode(mapping, selectorOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
ps, err := getProxies(proxies, selectorOption.Proxies)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||
}
|
||||
group, err = adapters.NewSelector(selectorOption.Name, ps)
|
||||
case "fallback":
|
||||
fallbackOption := &adapters.FallbackOption{}
|
||||
err = decoder.Decode(mapping, fallbackOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
ps, err := getProxies(proxies, fallbackOption.Proxies)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||
}
|
||||
group, err = adapters.NewFallback(*fallbackOption, ps)
|
||||
}
|
||||
if err != nil {
|
||||
return 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)
|
||||
|
||||
// close old goroutine
|
||||
for _, proxy := range c.proxies {
|
||||
switch raw := proxy.(type) {
|
||||
case *adapters.URLTest:
|
||||
raw.Close()
|
||||
case *adapters.Fallback:
|
||||
raw.Close()
|
||||
}
|
||||
}
|
||||
c.proxies = proxies
|
||||
c.event <- &Event{Type: "proxies", Payload: proxies}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Config) parseRules(cfg *ini.File) error {
|
||||
func (c *Config) parseRules(cfg *RawConfig) error {
|
||||
rules := []C.Rule{}
|
||||
|
||||
rulesConfig := cfg.Section("Rule")
|
||||
rulesConfig := cfg.Rule
|
||||
// parse rules
|
||||
for _, key := range rulesConfig.Keys() {
|
||||
rule := strings.Split(key.Name(), ",")
|
||||
for _, line := range rulesConfig {
|
||||
rule := strings.Split(line, ",")
|
||||
if len(rule) < 3 {
|
||||
continue
|
||||
}
|
||||
rule = trimArr(rule)
|
||||
switch rule[0] {
|
||||
case "DOMAIN":
|
||||
rules = append(rules, R.NewDomain(rule[1], rule[2]))
|
||||
case "DOMAIN-SUFFIX":
|
||||
rules = append(rules, R.NewDomainSuffix(rule[1], rule[2]))
|
||||
case "DOMAIN-KEYWORD":
|
||||
@ -330,17 +407,17 @@ func (c *Config) handleResponseMessage() {
|
||||
switch event.Type {
|
||||
case "http-addr":
|
||||
if event.Payload.(bool) == false {
|
||||
log.Errorf("Listening HTTP proxy at %s error", c.general.Port)
|
||||
log.Errorf("Listening HTTP proxy at %d error", c.general.Port)
|
||||
c.general.Port = 0
|
||||
}
|
||||
case "socks-addr":
|
||||
if event.Payload.(bool) == false {
|
||||
log.Errorf("Listening SOCKS proxy at %s error", c.general.SocksPort)
|
||||
log.Errorf("Listening SOCKS proxy at %d error", c.general.SocksPort)
|
||||
c.general.SocksPort = 0
|
||||
}
|
||||
case "redir-addr":
|
||||
if event.Payload.(bool) == false {
|
||||
log.Errorf("Listening Redir proxy at %s error", c.general.RedirPort)
|
||||
log.Errorf("Listening Redir proxy at %d error", c.general.RedirPort)
|
||||
c.general.RedirPort = 0
|
||||
}
|
||||
}
|
||||
|
@ -55,16 +55,23 @@ func downloadMMDB(path string) (err error) {
|
||||
|
||||
// Init prepare necessary files
|
||||
func Init() {
|
||||
// initial homedir
|
||||
if _, err := os.Stat(C.Path.HomeDir()); os.IsNotExist(err) {
|
||||
if err := os.MkdirAll(C.Path.HomeDir(), 0777); err != nil {
|
||||
log.Fatalf("Can't create config directory %s: %s", C.Path.HomeDir(), err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// initial config.ini
|
||||
if _, err := os.Stat(C.ConfigPath); os.IsNotExist(err) {
|
||||
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
||||
log.Info("Can't find config, create a empty file")
|
||||
os.OpenFile(C.ConfigPath, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
||||
}
|
||||
|
||||
// initial mmdb
|
||||
if _, err := os.Stat(C.MMDBPath); os.IsNotExist(err) {
|
||||
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||
log.Info("Can't find MMDB, start download")
|
||||
err := downloadMMDB(C.MMDBPath)
|
||||
err := downloadMMDB(C.Path.MMDB())
|
||||
if err != nil {
|
||||
log.Fatalf("Can't download MMDB: %s", err.Error())
|
||||
}
|
||||
|
@ -3,6 +3,8 @@ package config
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
func trimArr(arr []string) (r []string) {
|
||||
@ -18,3 +20,24 @@ func genAddr(port int, allowLan bool) string {
|
||||
}
|
||||
return fmt.Sprintf("127.0.0.1:%d", port)
|
||||
}
|
||||
|
||||
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
||||
var ps []C.Proxy
|
||||
for _, name := range list {
|
||||
p, ok := mapping[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("'%s' not found", name)
|
||||
}
|
||||
ps = append(ps, p)
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
func or(pointers ...*int) *int {
|
||||
for _, p := range pointers {
|
||||
if p != nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return pointers[len(pointers)-1]
|
||||
}
|
||||
|
@ -7,11 +7,13 @@ import (
|
||||
// Adapter Type
|
||||
const (
|
||||
Direct AdapterType = iota
|
||||
Fallback
|
||||
Reject
|
||||
Selector
|
||||
Shadowsocks
|
||||
Socks5
|
||||
URLTest
|
||||
Vmess
|
||||
)
|
||||
|
||||
type ProxyAdapter interface {
|
||||
@ -20,14 +22,14 @@ type ProxyAdapter interface {
|
||||
}
|
||||
|
||||
type ServerAdapter interface {
|
||||
Addr() *Addr
|
||||
Metadata() *Metadata
|
||||
Close()
|
||||
}
|
||||
|
||||
type Proxy interface {
|
||||
Name() string
|
||||
Type() AdapterType
|
||||
Generator(addr *Addr) (ProxyAdapter, error)
|
||||
Generator(metadata *Metadata) (ProxyAdapter, error)
|
||||
}
|
||||
|
||||
// AdapterType is enum of adapter type
|
||||
@ -37,6 +39,8 @@ func (at AdapterType) String() string {
|
||||
switch at {
|
||||
case Direct:
|
||||
return "Direct"
|
||||
case Fallback:
|
||||
return "Fallback"
|
||||
case Reject:
|
||||
return "Reject"
|
||||
case Selector:
|
||||
@ -47,6 +51,8 @@ func (at AdapterType) String() string {
|
||||
return "Socks5"
|
||||
case URLTest:
|
||||
return "URLTest"
|
||||
case Vmess:
|
||||
return "Vmess"
|
||||
default:
|
||||
return "Unknow"
|
||||
}
|
||||
|
@ -1,50 +1,10 @@
|
||||
package constant
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/user"
|
||||
"path"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
Name = "clash"
|
||||
)
|
||||
|
||||
var (
|
||||
HomeDir string
|
||||
ConfigPath string
|
||||
MMDBPath string
|
||||
)
|
||||
|
||||
type General struct {
|
||||
Mode *string `json:"mode,omitempty"`
|
||||
AllowLan *bool `json:"allow-lan,omitempty"`
|
||||
Port *int `json:"port,omitempty"`
|
||||
SocksPort *int `json:"socks-port,omitempty"`
|
||||
RedirPort *int `json:"redir-port,omitempty"`
|
||||
LogLevel *string `json:"log-level,omitempty"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
dir := os.Getenv("HOME")
|
||||
if dir == "" {
|
||||
log.Fatalf("Can't get current user: %s", err.Error())
|
||||
}
|
||||
HomeDir = dir
|
||||
} else {
|
||||
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")
|
||||
MMDBPath = path.Join(dirPath, "Country.mmdb")
|
||||
}
|
||||
|
@ -28,8 +28,8 @@ func (n *NetWork) String() string {
|
||||
|
||||
type SourceType int
|
||||
|
||||
// Addr is used to store connection address
|
||||
type Addr struct {
|
||||
// Metadata is used to store connection address
|
||||
type Metadata struct {
|
||||
NetWork NetWork
|
||||
Source SourceType
|
||||
AddrType int
|
||||
@ -38,7 +38,7 @@ type Addr struct {
|
||||
Port string
|
||||
}
|
||||
|
||||
func (addr *Addr) String() string {
|
||||
func (addr *Metadata) String() string {
|
||||
if addr.Host == "" {
|
||||
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
|
||||
const (
|
||||
DomainSuffix RuleType = iota
|
||||
Domain RuleType = iota
|
||||
DomainSuffix
|
||||
DomainKeyword
|
||||
GEOIP
|
||||
IPCIDR
|
||||
@ -13,6 +14,8 @@ type RuleType int
|
||||
|
||||
func (rt RuleType) String() string {
|
||||
switch rt {
|
||||
case Domain:
|
||||
return "Domain"
|
||||
case DomainSuffix:
|
||||
return "DomainSuffix"
|
||||
case DomainKeyword:
|
||||
@ -30,7 +33,7 @@ func (rt RuleType) String() string {
|
||||
|
||||
type Rule interface {
|
||||
RuleType() RuleType
|
||||
IsMatch(addr *Addr) bool
|
||||
IsMatch(metadata *Metadata) bool
|
||||
Adapter() string
|
||||
Payload() string
|
||||
}
|
||||
|
16
go.mod
Normal file
16
go.mod
Normal file
@ -0,0 +1,16 @@
|
||||
module github.com/Dreamacro/clash
|
||||
|
||||
require (
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.2-0.20181019110427-0a03f1a25270
|
||||
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/oschwald/geoip2-golang v1.2.1
|
||||
github.com/oschwald/maxminddb-golang v1.3.0 // indirect
|
||||
github.com/sirupsen/logrus v1.1.0
|
||||
golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941
|
||||
gopkg.in/eapache/channels.v1 v1.1.0
|
||||
gopkg.in/yaml.v2 v2.2.1
|
||||
)
|
41
go.sum
Normal file
41
go.sum
Normal file
@ -0,0 +1,41 @@
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.2-0.20181019110427-0a03f1a25270 h1:ugkI+Yw5ArFnhF8KTbJxyWIyvxMCa8jWyUF+wIAulhM=
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.2-0.20181019110427-0a03f1a25270/go.mod h1:DlkXRxmh5K+99aTPQaVjsZ1fAZNFw42vXGcOjR3Otps=
|
||||
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/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe h1:CHRGQ8V7OlCYtwaKPJi3iA7J+YdNKdo8j7nG5IgDhjs=
|
||||
github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
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.1.0 h1:65VZabgUiV9ktjGM5nTq0+YurgTyX+YI2lSSfDjI+qU=
|
||||
github.com/sirupsen/logrus v1.1.0/go.mod h1:zrgwTnHtNr00buQ1vSptGe8m1f/BbgsPukg8qsT7A+A=
|
||||
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-20181009213950-7c1a557ab941 h1:qBTHLajHecfu+xzRI9PqVDcqx7SdHj9d4B+EzSn3tAc=
|
||||
golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8=
|
||||
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.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
@ -21,6 +21,7 @@ func configRouter() http.Handler {
|
||||
type configSchema struct {
|
||||
Port int `json:"port"`
|
||||
SocksPort int `json:"socket-port"`
|
||||
RedirPort int `json:"redir-port"`
|
||||
AllowLan bool `json:"allow-lan"`
|
||||
Mode string `json:"mode"`
|
||||
LogLevel string `json:"log-level"`
|
||||
@ -31,6 +32,7 @@ func getConfigs(w http.ResponseWriter, r *http.Request) {
|
||||
render.JSON(w, r, configSchema{
|
||||
Port: general.Port,
|
||||
SocksPort: general.SocksPort,
|
||||
RedirPort: general.RedirPort,
|
||||
AllowLan: general.AllowLan,
|
||||
Mode: general.Mode.String(),
|
||||
LogLevel: general.LogLevel.String(),
|
||||
@ -87,6 +89,7 @@ func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
||||
AllowLan: general.AllowLan,
|
||||
Port: general.Port,
|
||||
SocksPort: general.SocksPort,
|
||||
RedirPort: general.RedirPort,
|
||||
})
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
A "github.com/Dreamacro/clash/adapters/remote"
|
||||
A "github.com/Dreamacro/clash/adapters/outbound"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
@ -37,6 +37,11 @@ type URLTest struct {
|
||||
Now string `json:"now"`
|
||||
}
|
||||
|
||||
type Fallback struct {
|
||||
Type string `json:"type"`
|
||||
Now string `json:"now"`
|
||||
}
|
||||
|
||||
func transformProxy(proxy C.Proxy) interface{} {
|
||||
t := proxy.Type()
|
||||
switch t {
|
||||
@ -52,6 +57,11 @@ func transformProxy(proxy C.Proxy) interface{} {
|
||||
Type: t.String(),
|
||||
Now: proxy.(*A.URLTest).Now(),
|
||||
}
|
||||
case C.Fallback:
|
||||
return Fallback{
|
||||
Type: t.String(),
|
||||
Now: proxy.(*A.Fallback).Now(),
|
||||
}
|
||||
default:
|
||||
return SampleProxy{
|
||||
Type: proxy.Type().String(),
|
||||
|
@ -17,6 +17,7 @@ func ruleRouter() http.Handler {
|
||||
type Rule struct {
|
||||
Name string `json:"name"`
|
||||
Payload string `json:"type"`
|
||||
Proxy string `json:"proxy"`
|
||||
}
|
||||
|
||||
type GetRulesResponse struct {
|
||||
@ -31,6 +32,7 @@ func getRules(w http.ResponseWriter, r *http.Request) {
|
||||
rules = append(rules, Rule{
|
||||
Name: rule.RuleType().String(),
|
||||
Payload: rule.Payload(),
|
||||
Proxy: rule.Adapter(),
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -3,6 +3,7 @@ package hub
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/config"
|
||||
@ -15,6 +16,8 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var secret = ""
|
||||
|
||||
type Traffic struct {
|
||||
Up int64 `json:"up"`
|
||||
Down int64 `json:"down"`
|
||||
@ -24,11 +27,19 @@ func newHub(signal chan struct{}) {
|
||||
var addr string
|
||||
ch := config.Instance().Subscribe()
|
||||
signal <- struct{}{}
|
||||
count := 0
|
||||
for {
|
||||
elm := <-ch
|
||||
event := elm.(*config.Event)
|
||||
if event.Type == "external-controller" {
|
||||
switch event.Type {
|
||||
case "external-controller":
|
||||
addr = event.Payload.(string)
|
||||
count++
|
||||
case "secret":
|
||||
secret = event.Payload.(string)
|
||||
count++
|
||||
}
|
||||
if count == 2 {
|
||||
break
|
||||
}
|
||||
}
|
||||
@ -38,11 +49,11 @@ func newHub(signal chan struct{}) {
|
||||
cors := cors.New(cors.Options{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Content-Type"},
|
||||
AllowedHeaders: []string{"Content-Type", "Authorization"},
|
||||
MaxAge: 300,
|
||||
})
|
||||
|
||||
r.Use(cors.Handler)
|
||||
r.Use(cors.Handler, authentication)
|
||||
|
||||
r.With(jsonContentType).Get("/traffic", traffic)
|
||||
r.With(jsonContentType).Get("/logs", getLogs)
|
||||
@ -65,6 +76,30 @@ func jsonContentType(next http.Handler) http.Handler {
|
||||
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 secret == "" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
hasUnvalidHeader := text[0] != "Bearer"
|
||||
hasUnvalidSecret := len(text) == 2 && text[1] != secret
|
||||
if hasUnvalidHeader || hasUnvalidSecret {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
render.JSON(w, r, Error{
|
||||
Error: "Authentication failed",
|
||||
})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func traffic(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
@ -82,23 +117,18 @@ func traffic(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
type GetLogs struct {
|
||||
Level string `json:"level"`
|
||||
}
|
||||
|
||||
type Log struct {
|
||||
Type string `json:"type"`
|
||||
Payload string `json:"payload"`
|
||||
}
|
||||
|
||||
func getLogs(w http.ResponseWriter, r *http.Request) {
|
||||
req := &GetLogs{}
|
||||
render.DecodeJSON(r.Body, req)
|
||||
if req.Level == "" {
|
||||
req.Level = "info"
|
||||
levelText := r.URL.Query().Get("level")
|
||||
if levelText == "" {
|
||||
levelText = "info"
|
||||
}
|
||||
|
||||
level, ok := C.LogLevelMapping[req.Level]
|
||||
level, ok := C.LogLevelMapping[levelText]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, Error{
|
||||
|
20
main.go
20
main.go
@ -4,20 +4,40 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"flag"
|
||||
"path"
|
||||
|
||||
"github.com/Dreamacro/clash/config"
|
||||
"github.com/Dreamacro/clash/hub"
|
||||
"github.com/Dreamacro/clash/proxy"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
homedir string
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&homedir, "d", "", "set configuration directory")
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
func main() {
|
||||
tunnel.Instance().Run()
|
||||
proxy.Instance().Run()
|
||||
hub.Run()
|
||||
|
||||
if (homedir != "") {
|
||||
if !path.IsAbs(homedir) {
|
||||
currentDir, _ := os.Getwd()
|
||||
homedir = path.Join(currentDir, homedir)
|
||||
}
|
||||
C.SetHomeDir(homedir)
|
||||
}
|
||||
|
||||
config.Init()
|
||||
err := config.Instance().Parse()
|
||||
if err != nil {
|
||||
|
@ -4,9 +4,8 @@ import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/local"
|
||||
"github.com/Dreamacro/clash/adapters/inbound"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
|
||||
@ -56,24 +55,20 @@ func NewHttpProxy(addr string) (*C.ProxySignal, error) {
|
||||
|
||||
func handleConn(conn net.Conn) {
|
||||
br := bufio.NewReader(conn)
|
||||
method, hostName := adapters.ParserHTTPHostHeader(br)
|
||||
if hostName == "" {
|
||||
request, err := http.ReadRequest(br)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.Contains(hostName, ":") {
|
||||
hostName += ":80"
|
||||
}
|
||||
|
||||
var peeked []byte
|
||||
if method == http.MethodConnect {
|
||||
if request.Method == http.MethodConnect {
|
||||
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
} else if n := br.Buffered(); n > 0 {
|
||||
peeked, _ = br.Peek(br.Buffered())
|
||||
tun.Add(adapters.NewHTTPS(request, conn))
|
||||
return
|
||||
}
|
||||
|
||||
tun.Add(adapters.NewHTTP(hostName, peeked, method != http.MethodConnect, conn))
|
||||
tun.Add(adapters.NewHTTP(request, conn))
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ package redir
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/local"
|
||||
"github.com/Dreamacro/clash/adapters/inbound"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
|
||||
@ -58,5 +58,5 @@ func handleRedir(conn net.Conn) {
|
||||
return
|
||||
}
|
||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||
tun.Add(adapters.NewSocks(target, conn))
|
||||
tun.Add(adapters.NewSocket(target, conn))
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
func parserPacket(c net.Conn) (socks.Addr, error) {
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
|
@ -3,11 +3,11 @@ package socks
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/local"
|
||||
"github.com/Dreamacro/clash/adapters/inbound"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
|
||||
"github.com/riobard/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@ -59,5 +59,5 @@ func handleSocks(conn net.Conn) {
|
||||
return
|
||||
}
|
||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||
tun.Add(adapters.NewSocks(target, conn))
|
||||
tun.Add(adapters.NewSocket(target, conn))
|
||||
}
|
||||
|
36
rules/domain.go
Normal file
36
rules/domain.go
Normal file
@ -0,0 +1,36 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
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: domain,
|
||||
adapter: adapter,
|
||||
}
|
||||
}
|
@ -15,11 +15,11 @@ func (dk *DomainKeyword) RuleType() C.RuleType {
|
||||
return C.DomainKeyword
|
||||
}
|
||||
|
||||
func (dk *DomainKeyword) IsMatch(addr *C.Addr) bool {
|
||||
if addr.AddrType != C.AtypDomainName {
|
||||
func (dk *DomainKeyword) IsMatch(metadata *C.Metadata) bool {
|
||||
if metadata.AddrType != C.AtypDomainName {
|
||||
return false
|
||||
}
|
||||
domain := addr.Host
|
||||
domain := metadata.Host
|
||||
return strings.Contains(domain, dk.keyword)
|
||||
}
|
||||
|
||||
|
@ -15,11 +15,11 @@ func (ds *DomainSuffix) RuleType() C.RuleType {
|
||||
return C.DomainSuffix
|
||||
}
|
||||
|
||||
func (ds *DomainSuffix) IsMatch(addr *C.Addr) bool {
|
||||
if addr.AddrType != C.AtypDomainName {
|
||||
func (ds *DomainSuffix) IsMatch(metadata *C.Metadata) bool {
|
||||
if metadata.AddrType != C.AtypDomainName {
|
||||
return false
|
||||
}
|
||||
domain := addr.Host
|
||||
domain := metadata.Host
|
||||
return strings.HasSuffix(domain, "."+ds.suffix) || domain == ds.suffix
|
||||
}
|
||||
|
||||
|
@ -12,7 +12,7 @@ func (f *Final) RuleType() C.RuleType {
|
||||
return C.FINAL
|
||||
}
|
||||
|
||||
func (f *Final) IsMatch(addr *C.Addr) bool {
|
||||
func (f *Final) IsMatch(metadata *C.Metadata) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
|
@ -23,11 +23,11 @@ func (g *GEOIP) RuleType() C.RuleType {
|
||||
return C.GEOIP
|
||||
}
|
||||
|
||||
func (g *GEOIP) IsMatch(addr *C.Addr) bool {
|
||||
if addr.IP == nil {
|
||||
func (g *GEOIP) IsMatch(metadata *C.Metadata) bool {
|
||||
if metadata.IP == nil {
|
||||
return false
|
||||
}
|
||||
record, _ := mmdb.Country(*addr.IP)
|
||||
record, _ := mmdb.Country(*metadata.IP)
|
||||
return record.Country.IsoCode == g.country
|
||||
}
|
||||
|
||||
@ -42,7 +42,7 @@ func (g *GEOIP) Payload() string {
|
||||
func NewGEOIP(country string, adapter string) *GEOIP {
|
||||
once.Do(func() {
|
||||
var err error
|
||||
mmdb, err = geoip2.Open(C.MMDBPath)
|
||||
mmdb, err = geoip2.Open(C.Path.MMDB())
|
||||
if err != nil {
|
||||
log.Fatalf("Can't load mmdb: %s", err.Error())
|
||||
}
|
||||
|
@ -15,12 +15,12 @@ func (i *IPCIDR) RuleType() C.RuleType {
|
||||
return C.IPCIDR
|
||||
}
|
||||
|
||||
func (i *IPCIDR) IsMatch(addr *C.Addr) bool {
|
||||
if addr.IP == nil {
|
||||
func (i *IPCIDR) IsMatch(metadata *C.Metadata) bool {
|
||||
if metadata.IP == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return i.ipnet.Contains(*addr.IP)
|
||||
return i.ipnet.Contains(*metadata.IP)
|
||||
}
|
||||
|
||||
func (i *IPCIDR) Adapter() string {
|
||||
|
@ -1,29 +1,77 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/local"
|
||||
"github.com/Dreamacro/clash/adapters/inbound"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter) {
|
||||
conn := newTrafficTrack(proxy.Conn(), t.traffic)
|
||||
req := request.R
|
||||
host := req.Host
|
||||
|
||||
// Before we unwrap src and/or dst, copy any buffered data.
|
||||
if wc, ok := request.Conn().(*adapters.PeekedConn); ok && len(wc.Peeked) > 0 {
|
||||
if _, err := conn.Write(wc.Peeked); err != nil {
|
||||
return
|
||||
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
|
||||
}
|
||||
wc.Peeked = nil
|
||||
}
|
||||
|
||||
go io.Copy(request.Conn(), conn)
|
||||
io.Copy(conn, request.Conn())
|
||||
}
|
||||
|
||||
func (t *Tunnel) handleSOCKS(request *adapters.SocksAdapter, proxy C.ProxyAdapter) {
|
||||
func (t *Tunnel) handleSOCKS(request *adapters.SocketAdapter, proxy C.ProxyAdapter) {
|
||||
conn := newTrafficTrack(proxy.Conn(), t.traffic)
|
||||
go io.Copy(request.Conn(), conn)
|
||||
io.Copy(conn, request.Conn())
|
||||
relay(request.Conn(), conn)
|
||||
}
|
||||
|
||||
// relay copies between left and right bidirectionally.
|
||||
func relay(leftConn, rightConn net.Conn) {
|
||||
ch := make(chan error)
|
||||
|
||||
go func() {
|
||||
_, err := io.Copy(leftConn, rightConn)
|
||||
leftConn.SetReadDeadline(time.Now())
|
||||
ch <- err
|
||||
}()
|
||||
|
||||
io.Copy(rightConn, leftConn)
|
||||
rightConn.SetReadDeadline(time.Now())
|
||||
<-ch
|
||||
}
|
||||
|
@ -4,10 +4,10 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
LocalAdapter "github.com/Dreamacro/clash/adapters/local"
|
||||
InboundAdapter "github.com/Dreamacro/clash/adapters/inbound"
|
||||
"github.com/Dreamacro/clash/common/observable"
|
||||
cfg "github.com/Dreamacro/clash/config"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/observable"
|
||||
|
||||
"gopkg.in/eapache/channels.v1"
|
||||
)
|
||||
@ -84,7 +84,7 @@ func (t *Tunnel) process() {
|
||||
|
||||
func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
||||
defer localConn.Close()
|
||||
addr := localConn.Addr()
|
||||
metadata := localConn.Metadata()
|
||||
|
||||
var proxy C.Proxy
|
||||
switch t.mode {
|
||||
@ -94,9 +94,9 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
||||
proxy = t.proxies["GLOBAL"]
|
||||
// Rule
|
||||
default:
|
||||
proxy = t.match(addr)
|
||||
proxy = t.match(metadata)
|
||||
}
|
||||
remoConn, err := proxy.Generator(addr)
|
||||
remoConn, err := proxy.Generator(metadata)
|
||||
if err != nil {
|
||||
t.logCh <- newLog(C.WARNING, "Proxy connect error: %s", err.Error())
|
||||
return
|
||||
@ -104,28 +104,28 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
||||
defer remoConn.Close()
|
||||
|
||||
switch adapter := localConn.(type) {
|
||||
case *LocalAdapter.HTTPAdapter:
|
||||
case *InboundAdapter.HTTPAdapter:
|
||||
t.handleHTTP(adapter, remoConn)
|
||||
case *LocalAdapter.SocksAdapter:
|
||||
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()
|
||||
defer t.configLock.RUnlock()
|
||||
|
||||
for _, rule := range t.rules {
|
||||
if rule.IsMatch(addr) {
|
||||
if rule.IsMatch(metadata) {
|
||||
a, ok := t.proxies[rule.Adapter()]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
t.logCh <- newLog(C.INFO, "%v match %s using %s", addr.String(), rule.RuleType().String(), rule.Adapter())
|
||||
t.logCh <- newLog(C.INFO, "%v match %s using %s", metadata.String(), rule.RuleType().String(), rule.Adapter())
|
||||
return a
|
||||
}
|
||||
}
|
||||
t.logCh <- newLog(C.INFO, "%v doesn't match any rule using DIRECT", addr.String())
|
||||
t.logCh <- newLog(C.INFO, "%v doesn't match any rule using DIRECT", metadata.String())
|
||||
return t.proxies["DIRECT"]
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user