Compare commits
65 Commits
Author | SHA1 | Date | |
---|---|---|---|
34338e7107 | |||
57fdd223f1 | |||
bc3fc0c840 | |||
662038e40e | |||
53528f8275 | |||
1c792b46c9 | |||
2417cfda12 | |||
aa3516ca24 | |||
bcf5b21208 | |||
ba5eefb6dd | |||
407de7388c | |||
6adafde9a0 | |||
cba548114f | |||
016e7bd0b4 | |||
ad13ad8dba | |||
89168e6c96 | |||
a4b8e286db | |||
e837470a6a | |||
b589754485 | |||
0eccbb023c | |||
71a08ad8e2 | |||
0d4a999707 | |||
243d8a2844 | |||
225c530d13 | |||
cff4841f3e | |||
f352f4479e | |||
762f227512 | |||
936ea3aa55 | |||
cec2206774 | |||
90e3dccacd | |||
c92cda6980 | |||
49f8902961 | |||
7770e18430 | |||
593a63c228 | |||
744728cb84 | |||
2036f8cb7a | |||
531f487629 | |||
18f885a92a | |||
d3b280a7e5 | |||
d1f6886558 | |||
791d72e05b | |||
14600a8170 | |||
bb267e4a1f | |||
f99da37168 | |||
7a9d986ff3 | |||
63446da5fa | |||
acf55a7f64 | |||
8c608f5d7a | |||
7f0c7d7802 | |||
7683271fe6 | |||
23bb01a4df | |||
0011c7acfe | |||
d75f9ff783 | |||
815e80f720 | |||
ca5399a16e | |||
04927229ff | |||
c0bd82d62b | |||
5c8bb24121 | |||
575720e0cc | |||
e7997a035b | |||
287ad5bc53 | |||
c295c5e412 | |||
8636a4f589 | |||
7a0717830c | |||
5920b05752 |
@ -1,7 +1,7 @@
|
||||
language: go
|
||||
sudo: false
|
||||
go:
|
||||
- "1.11"
|
||||
- '1.12'
|
||||
install:
|
||||
- "go mod download"
|
||||
env:
|
||||
|
@ -18,6 +18,4 @@ RUN apk add --no-cache ca-certificates
|
||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||
COPY --from=builder /clash /
|
||||
|
||||
EXPOSE 7890 7891
|
||||
|
||||
ENTRYPOINT ["/clash"]
|
||||
|
12
Makefile
12
Makefile
@ -1,6 +1,10 @@
|
||||
NAME=clash
|
||||
BINDIR=bin
|
||||
GOBUILD=CGO_ENABLED=0 go build -ldflags '-w -s'
|
||||
VERSION=$(shell git describe --tags || echo "unknown version")
|
||||
BUILDTIME=$(shell date -u)
|
||||
GOBUILD=CGO_ENABLED=0 go build -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||
-w -s'
|
||||
|
||||
PLATFORM_LIST = \
|
||||
darwin-amd64 \
|
||||
@ -67,7 +71,7 @@ freebsd-amd64:
|
||||
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
windows-386:
|
||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
|
||||
windows-amd64:
|
||||
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
@ -77,10 +81,10 @@ zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
||||
|
||||
$(gz_releases): %.gz : %
|
||||
chmod +x $(BINDIR)/$(NAME)-$(basename $@)
|
||||
gzip -f $(BINDIR)/$(NAME)-$(basename $@)
|
||||
gzip -f -S -$(VERSION).gz $(BINDIR)/$(NAME)-$(basename $@)
|
||||
|
||||
$(zip_releases): %.zip : %
|
||||
zip -m -j $(BINDIR)/$(NAME)-$(basename $@).zip $(BINDIR)/$(NAME)-$(basename $@).exe
|
||||
zip -m -j $(BINDIR)/$(NAME)-$(basename $@)-$(VERSION).zip $(BINDIR)/$(NAME)-$(basename $@).exe
|
||||
|
||||
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
||||
|
||||
|
50
README.md
50
README.md
@ -36,7 +36,13 @@ go get -u -v github.com/Dreamacro/clash
|
||||
|
||||
Pre-built binaries are available: [release](https://github.com/Dreamacro/clash/releases)
|
||||
|
||||
Requires Go >= 1.11.
|
||||
Requires Go >= 1.12.
|
||||
|
||||
Checkout Clash version:
|
||||
|
||||
```sh
|
||||
clash -v
|
||||
```
|
||||
|
||||
## Daemon
|
||||
|
||||
@ -58,7 +64,7 @@ If you have Docker installed, you can run clash directly using `docker-compose`.
|
||||
|
||||
The default configuration directory is `$HOME/.config/clash`
|
||||
|
||||
The name of the configuration file is `config.yml`
|
||||
The name of the configuration file is `config.yaml`
|
||||
|
||||
If you want to use another directory, you can use `-d` to control the configuration directory
|
||||
|
||||
@ -99,16 +105,27 @@ external-controller: 127.0.0.1:9090
|
||||
# Secret for RESTful API (Optional)
|
||||
# secret: ""
|
||||
|
||||
# experimental feature
|
||||
experimental:
|
||||
ignore-resolve-fail: true # ignore dns resolve fail, default value is true
|
||||
|
||||
# authentication of local SOCKS5/HTTP(S) server
|
||||
# authentication:
|
||||
# - "user1:pass1"
|
||||
# - "user2:pass2"
|
||||
|
||||
# dns:
|
||||
# enable: true # set true to enable dns (default is false)
|
||||
# ipv6: false # default is false
|
||||
# listen: 0.0.0.0:53
|
||||
# enhanced-mode: redir-host
|
||||
# enhanced-mode: redir-host # or fake-ip
|
||||
# # fake-ip-range: 198.18.0.1/16 # if you don't know what it is, don't change it
|
||||
# nameserver:
|
||||
# - 114.114.114.114
|
||||
# - tls://dns.rubyfish.cn:853 # dns over tls
|
||||
# - https://1.1.1.1/dns-query # dns over https
|
||||
# fallback: # concurrent request with nameserver, fallback used when GEOIP country isn't CN
|
||||
# - 8.8.8.8
|
||||
# - tcp://1.1.1.1
|
||||
|
||||
Proxy:
|
||||
|
||||
@ -116,7 +133,7 @@ Proxy:
|
||||
# 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
|
||||
# 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: "ss1", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password", udp: true }
|
||||
|
||||
# old obfs configuration remove after prerelease
|
||||
- name: "ss2"
|
||||
@ -143,6 +160,8 @@ Proxy:
|
||||
# skip-cert-verify: true
|
||||
# host: bing.com
|
||||
# path: "/"
|
||||
# headers:
|
||||
# custom: value
|
||||
|
||||
# vmess
|
||||
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
|
||||
@ -181,23 +200,32 @@ Proxy Group:
|
||||
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
|
||||
- { name: "fallback-auto", type: fallback, proxies: ["ss1", "ss2", "vmess1"], url: "http://www.gstatic.com/generate_204", interval: 300 }
|
||||
|
||||
# load-balance: The request of the same eTLD will be dial on the same proxy.
|
||||
- { name: "load-balance", type: load-balance, proxies: ["ss1", "ss2", "vmess1"], url: "http://www.gstatic.com/generate_204", interval: 300 }
|
||||
|
||||
# select is used for selecting proxy or proxy group
|
||||
# you can use RESTful API to switch proxy, is recommended for use in GUI.
|
||||
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
|
||||
|
||||
Rule:
|
||||
- DOMAIN-SUFFIX,google.com,Proxy
|
||||
- DOMAIN-KEYWORD,google,Proxy
|
||||
- DOMAIN,google.com,Proxy
|
||||
- DOMAIN-SUFFIX,google.com,auto
|
||||
- DOMAIN-KEYWORD,google,auto
|
||||
- DOMAIN,google.com,auto
|
||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
||||
- IP-CIDR,127.0.0.0/8,DIRECT
|
||||
- SOURCE-IP-CIDR,192.168.1.201/32,DIRECT
|
||||
# rename SOURCE-IP-CIDR and would remove after prerelease
|
||||
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
||||
- GEOIP,CN,DIRECT
|
||||
- DST-PORT,80,DIRECT
|
||||
- SRC-PORT,7777,DIRECT
|
||||
# FINAL would remove after prerelease
|
||||
# you also can use `FINAL,Proxy` or `FINAL,,Proxy` now
|
||||
- MATCH,Proxy
|
||||
- MATCH,auto
|
||||
```
|
||||
|
||||
## Documentations
|
||||
https://clash.gitbook.io/
|
||||
|
||||
## Thanks
|
||||
|
||||
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||
@ -212,5 +240,5 @@ Rule:
|
||||
|
||||
- [x] Complementing the necessary rule operators
|
||||
- [x] Redir proxy
|
||||
- [ ] UDP support
|
||||
- [x] UDP support
|
||||
- [ ] Connection manager
|
||||
|
@ -10,34 +10,27 @@ import (
|
||||
|
||||
// HTTPAdapter is a adapter for HTTP connection
|
||||
type HTTPAdapter struct {
|
||||
net.Conn
|
||||
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 {
|
||||
metadata := parseHTTPAddr(request)
|
||||
metadata.SourceIP = parseSourceIP(conn)
|
||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
return &HTTPAdapter{
|
||||
metadata: metadata,
|
||||
R: request,
|
||||
conn: conn,
|
||||
Conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -8,9 +8,12 @@ import (
|
||||
// NewHTTPS is HTTPAdapter generator
|
||||
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
||||
metadata := parseHTTPAddr(request)
|
||||
metadata.SourceIP = parseSourceIP(conn)
|
||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
return &SocketAdapter{
|
||||
metadata: metadata,
|
||||
conn: conn,
|
||||
Conn: conn,
|
||||
}
|
||||
}
|
||||
|
@ -3,39 +3,33 @@ package adapters
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
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
|
||||
net.Conn
|
||||
metadata *C.Metadata
|
||||
}
|
||||
|
||||
// Close socks and redir connection
|
||||
func (s *SocketAdapter) Close() {
|
||||
s.conn.Close()
|
||||
}
|
||||
|
||||
// Metadata return destination metadata
|
||||
func (s *SocketAdapter) Metadata() *C.Metadata {
|
||||
return s.metadata
|
||||
}
|
||||
|
||||
// Conn return raw net.Conn
|
||||
func (s *SocketAdapter) Conn() net.Conn {
|
||||
return s.conn
|
||||
}
|
||||
|
||||
// NewSocket is SocketAdapter generator
|
||||
func NewSocket(target socks.Addr, conn net.Conn, source C.SourceType) *SocketAdapter {
|
||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, netType C.NetWork) *SocketAdapter {
|
||||
metadata := parseSocksAddr(target)
|
||||
metadata.Source = source
|
||||
metadata.SourceIP = parseSourceIP(conn)
|
||||
metadata.NetWork = netType
|
||||
metadata.Type = source
|
||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
|
||||
return &SocketAdapter{
|
||||
conn: conn,
|
||||
Conn: conn,
|
||||
metadata: metadata,
|
||||
}
|
||||
}
|
||||
|
@ -5,28 +5,27 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
func parseSocksAddr(target socks.Addr) *C.Metadata {
|
||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||
metadata := &C.Metadata{
|
||||
NetWork: C.TCP,
|
||||
AddrType: int(target[0]),
|
||||
}
|
||||
|
||||
switch target[0] {
|
||||
case socks.AtypDomainName:
|
||||
case socks5.AtypDomainName:
|
||||
metadata.Host = string(target[2 : 2+target[1]])
|
||||
metadata.Port = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||
case socks.AtypIPv4:
|
||||
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||
case socks5.AtypIPv4:
|
||||
ip := net.IP(target[1 : 1+net.IPv4len])
|
||||
metadata.IP = &ip
|
||||
metadata.Port = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||
case socks.AtypIPv6:
|
||||
metadata.DstIP = &ip
|
||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||
case socks5.AtypIPv6:
|
||||
ip := net.IP(target[1 : 1+net.IPv6len])
|
||||
metadata.IP = &ip
|
||||
metadata.Port = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||
metadata.DstIP = &ip
|
||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||
}
|
||||
|
||||
return metadata
|
||||
@ -41,11 +40,11 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||
|
||||
metadata := &C.Metadata{
|
||||
NetWork: C.TCP,
|
||||
Source: C.HTTP,
|
||||
Type: C.HTTP,
|
||||
AddrType: C.AtypDomainName,
|
||||
Host: host,
|
||||
IP: nil,
|
||||
Port: port,
|
||||
DstIP: nil,
|
||||
DstPort: port,
|
||||
}
|
||||
|
||||
ip := net.ParseIP(host)
|
||||
@ -56,15 +55,18 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||
default:
|
||||
metadata.AddrType = C.AtypIPv4
|
||||
}
|
||||
metadata.IP = &ip
|
||||
metadata.DstIP = &ip
|
||||
}
|
||||
|
||||
return metadata
|
||||
}
|
||||
|
||||
func parseSourceIP(conn net.Conn) *net.IP {
|
||||
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
|
||||
return &addr.IP
|
||||
func parseAddr(addr string) (*net.IP, string, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return nil
|
||||
|
||||
ip := net.ParseIP(host)
|
||||
return &ip, port, nil
|
||||
}
|
||||
|
@ -2,13 +2,19 @@ package adapters
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/queue"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
name string
|
||||
tp C.AdapterType
|
||||
udp bool
|
||||
}
|
||||
|
||||
func (b *Base) Name() string {
|
||||
@ -19,8 +25,124 @@ func (b *Base) Type() C.AdapterType {
|
||||
return b.tp
|
||||
}
|
||||
|
||||
func (b *Base) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
return nil, nil, errors.New("no support")
|
||||
}
|
||||
|
||||
func (b *Base) SupportUDP() bool {
|
||||
return b.udp
|
||||
}
|
||||
|
||||
func (b *Base) Destroy() {}
|
||||
|
||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(map[string]string{
|
||||
"type": b.Type().String(),
|
||||
})
|
||||
}
|
||||
|
||||
type Proxy struct {
|
||||
C.ProxyAdapter
|
||||
history *queue.Queue
|
||||
alive bool
|
||||
}
|
||||
|
||||
func (p *Proxy) Alive() bool {
|
||||
return p.alive
|
||||
}
|
||||
|
||||
func (p *Proxy) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
conn, err := p.ProxyAdapter.Dial(metadata)
|
||||
if err != nil {
|
||||
p.alive = false
|
||||
}
|
||||
return conn, err
|
||||
}
|
||||
|
||||
func (p *Proxy) DelayHistory() []C.DelayHistory {
|
||||
queue := p.history.Copy()
|
||||
histories := []C.DelayHistory{}
|
||||
for _, item := range queue {
|
||||
histories = append(histories, item.(C.DelayHistory))
|
||||
}
|
||||
return histories
|
||||
}
|
||||
|
||||
// LastDelay return last history record. if proxy is not alive, return the max value of int16.
|
||||
func (p *Proxy) LastDelay() (delay uint16) {
|
||||
var max uint16 = 0xffff
|
||||
if !p.alive {
|
||||
return max
|
||||
}
|
||||
|
||||
head := p.history.First()
|
||||
if head == nil {
|
||||
return max
|
||||
}
|
||||
history := head.(C.DelayHistory)
|
||||
if history.Delay == 0 {
|
||||
return max
|
||||
}
|
||||
return history.Delay
|
||||
}
|
||||
|
||||
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||
inner, err := p.ProxyAdapter.MarshalJSON()
|
||||
if err != nil {
|
||||
return inner, err
|
||||
}
|
||||
|
||||
mapping := map[string]interface{}{}
|
||||
json.Unmarshal(inner, &mapping)
|
||||
mapping["history"] = p.DelayHistory()
|
||||
return json.Marshal(mapping)
|
||||
}
|
||||
|
||||
// URLTest get the delay for the specified URL
|
||||
func (p *Proxy) URLTest(url string) (t uint16, err error) {
|
||||
defer func() {
|
||||
p.alive = err == nil
|
||||
record := C.DelayHistory{Time: time.Now()}
|
||||
if err == nil {
|
||||
record.Delay = t
|
||||
}
|
||||
p.history.Put(record)
|
||||
if p.history.Len() > 10 {
|
||||
p.history.Pop()
|
||||
}
|
||||
}()
|
||||
|
||||
addr, err := urlToMetadata(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
instance, err := p.Dial(&addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer instance.Close()
|
||||
transport := &http.Transport{
|
||||
Dial: func(string, string) (net.Conn, error) {
|
||||
return instance, nil
|
||||
},
|
||||
// from http.DefaultTransport
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
client := http.Client{Transport: transport}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resp.Body.Close()
|
||||
t = uint16(time.Since(start) / time.Millisecond)
|
||||
return
|
||||
}
|
||||
|
||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||
return &Proxy{adapter, queue.New(10), true}
|
||||
}
|
||||
|
@ -10,13 +10,13 @@ type Direct struct {
|
||||
*Base
|
||||
}
|
||||
|
||||
func (d *Direct) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
address := net.JoinHostPort(metadata.Host, metadata.Port)
|
||||
if metadata.IP != nil {
|
||||
address = net.JoinHostPort(metadata.IP.String(), metadata.Port)
|
||||
func (d *Direct) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
address := net.JoinHostPort(metadata.Host, metadata.DstPort)
|
||||
if metadata.DstIP != nil {
|
||||
address = net.JoinHostPort(metadata.DstIP.String(), metadata.DstPort)
|
||||
}
|
||||
|
||||
c, err := net.DialTimeout("tcp", address, tcpTimeout)
|
||||
c, err := dialTimeout("tcp", address, tcpTimeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -24,11 +24,25 @@ func (d *Direct) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (d *Direct) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
pc, err := net.ListenPacket("udp", "")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
addr, err := resolveUDPAddr("udp", net.JoinHostPort(metadata.String(), metadata.DstPort))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return pc, addr, nil
|
||||
}
|
||||
|
||||
func NewDirect() *Direct {
|
||||
return &Direct{
|
||||
Base: &Base{
|
||||
name: "DIRECT",
|
||||
tp: C.Direct,
|
||||
udp: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -10,14 +10,9 @@ import (
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type proxy struct {
|
||||
RawProxy C.Proxy
|
||||
Valid bool
|
||||
}
|
||||
|
||||
type Fallback struct {
|
||||
*Base
|
||||
proxies []*proxy
|
||||
proxies []C.Proxy
|
||||
rawURL string
|
||||
interval time.Duration
|
||||
done chan struct{}
|
||||
@ -31,36 +26,29 @@ type FallbackOption struct {
|
||||
}
|
||||
|
||||
func (f *Fallback) Now() string {
|
||||
_, proxy := f.findNextValidProxy(0)
|
||||
if proxy != nil {
|
||||
return proxy.RawProxy.Name()
|
||||
}
|
||||
return f.proxies[0].RawProxy.Name()
|
||||
proxy := f.findAliveProxy()
|
||||
return proxy.Name()
|
||||
}
|
||||
|
||||
func (f *Fallback) Generator(metadata *C.Metadata) (net.Conn, 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 adapter, err
|
||||
}
|
||||
return f.proxies[0].RawProxy.Generator(metadata)
|
||||
func (f *Fallback) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
proxy := f.findAliveProxy()
|
||||
return proxy.Dial(metadata)
|
||||
}
|
||||
|
||||
func (f *Fallback) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
proxy := f.findAliveProxy()
|
||||
return proxy.DialUDP(metadata)
|
||||
}
|
||||
|
||||
func (f *Fallback) SupportUDP() bool {
|
||||
proxy := f.findAliveProxy()
|
||||
return proxy.SupportUDP()
|
||||
}
|
||||
|
||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range f.proxies {
|
||||
all = append(all, proxy.RawProxy.Name())
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]interface{}{
|
||||
"type": f.Type().String(),
|
||||
@ -69,7 +57,7 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (f *Fallback) Close() {
|
||||
func (f *Fallback) Destroy() {
|
||||
f.done <- struct{}{}
|
||||
}
|
||||
|
||||
@ -87,13 +75,13 @@ 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]
|
||||
func (f *Fallback) findAliveProxy() C.Proxy {
|
||||
for _, proxy := range f.proxies {
|
||||
if proxy.Alive() {
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
return -1, nil
|
||||
return f.proxies[0]
|
||||
}
|
||||
|
||||
func (f *Fallback) validTest() {
|
||||
@ -101,9 +89,8 @@ func (f *Fallback) validTest() {
|
||||
wg.Add(len(f.proxies))
|
||||
|
||||
for _, p := range f.proxies {
|
||||
go func(p *proxy) {
|
||||
_, err := DelayTest(p.RawProxy, f.rawURL)
|
||||
p.Valid = err == nil
|
||||
go func(p C.Proxy) {
|
||||
p.URLTest(f.rawURL)
|
||||
wg.Done()
|
||||
}(p)
|
||||
}
|
||||
@ -122,20 +109,13 @@ func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
||||
}
|
||||
|
||||
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{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Fallback,
|
||||
},
|
||||
proxies: warpperProxies,
|
||||
proxies: proxies,
|
||||
rawURL: option.URL,
|
||||
interval: interval,
|
||||
done: make(chan struct{}),
|
||||
|
@ -35,8 +35,8 @@ type HttpOption struct {
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
}
|
||||
|
||||
func (h *Http) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := net.DialTimeout("tcp", h.addr, tcpTimeout)
|
||||
func (h *Http) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := dialTimeout("tcp", h.addr, tcpTimeout)
|
||||
if err == nil && h.tls {
|
||||
cc := tls.Client(c, h.tlsConfig)
|
||||
err = cc.Handshake()
|
||||
@ -58,9 +58,9 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||
var buf bytes.Buffer
|
||||
var err error
|
||||
|
||||
addr := net.JoinHostPort(metadata.Host, metadata.Port)
|
||||
addr := net.JoinHostPort(metadata.String(), metadata.DstPort)
|
||||
buf.WriteString("CONNECT " + addr + " HTTP/1.1\r\n")
|
||||
buf.WriteString("Host: " + metadata.Host + "\r\n")
|
||||
buf.WriteString("Host: " + metadata.String() + "\r\n")
|
||||
buf.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
||||
|
||||
if h.user != "" && h.pass != "" {
|
||||
@ -101,8 +101,6 @@ func NewHttp(option HttpOption) *Http {
|
||||
tlsConfig = &tls.Config{
|
||||
InsecureSkipVerify: option.SkipCertVerify,
|
||||
ClientSessionCache: getClientSessionCache(),
|
||||
MinVersion: tls.VersionTLS11,
|
||||
MaxVersion: tls.VersionTLS12,
|
||||
ServerName: option.Server,
|
||||
}
|
||||
}
|
||||
|
158
adapters/outbound/loadbalance.go
Normal file
158
adapters/outbound/loadbalance.go
Normal file
@ -0,0 +1,158 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/murmur3"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
type LoadBalance struct {
|
||||
*Base
|
||||
proxies []C.Proxy
|
||||
maxRetry int
|
||||
rawURL string
|
||||
interval time.Duration
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func getKey(metadata *C.Metadata) string {
|
||||
if metadata.Host != "" {
|
||||
// ip host
|
||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||
return metadata.Host
|
||||
}
|
||||
|
||||
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
|
||||
return etld
|
||||
}
|
||||
}
|
||||
|
||||
if metadata.DstIP == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return metadata.DstIP.String()
|
||||
}
|
||||
|
||||
func jumpHash(key uint64, buckets int32) int32 {
|
||||
var b, j int64
|
||||
|
||||
for j < int64(buckets) {
|
||||
b = j
|
||||
key = key*2862933555777941757 + 1
|
||||
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
|
||||
}
|
||||
|
||||
return int32(b)
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||
buckets := int32(len(lb.proxies))
|
||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||
idx := jumpHash(key, buckets)
|
||||
proxy := lb.proxies[idx]
|
||||
if proxy.Alive() {
|
||||
return proxy.Dial(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
return lb.proxies[0].Dial(metadata)
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||
buckets := int32(len(lb.proxies))
|
||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||
idx := jumpHash(key, buckets)
|
||||
proxy := lb.proxies[idx]
|
||||
if proxy.Alive() {
|
||||
return proxy.DialUDP(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
return lb.proxies[0].DialUDP(metadata)
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) SupportUDP() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) Destroy() {
|
||||
lb.done <- struct{}{}
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) validTest() {
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(lb.proxies))
|
||||
|
||||
for _, p := range lb.proxies {
|
||||
go func(p C.Proxy) {
|
||||
p.URLTest(lb.rawURL)
|
||||
wg.Done()
|
||||
}(p)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) loop() {
|
||||
tick := time.NewTicker(lb.interval)
|
||||
go lb.validTest()
|
||||
Loop:
|
||||
for {
|
||||
select {
|
||||
case <-tick.C:
|
||||
go lb.validTest()
|
||||
case <-lb.done:
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range lb.proxies {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
return json.Marshal(map[string]interface{}{
|
||||
"type": lb.Type().String(),
|
||||
"all": all,
|
||||
})
|
||||
}
|
||||
|
||||
type LoadBalanceOption struct {
|
||||
Name string `proxy:"name"`
|
||||
Proxies []string `proxy:"proxies"`
|
||||
URL string `proxy:"url"`
|
||||
Interval int `proxy:"interval"`
|
||||
}
|
||||
|
||||
func NewLoadBalance(option LoadBalanceOption, proxies []C.Proxy) (*LoadBalance, error) {
|
||||
if len(proxies) == 0 {
|
||||
return nil, errors.New("Provide at least one proxy")
|
||||
}
|
||||
|
||||
interval := time.Duration(option.Interval) * time.Second
|
||||
|
||||
lb := &LoadBalance{
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.LoadBalance,
|
||||
},
|
||||
proxies: proxies,
|
||||
maxRetry: 3,
|
||||
rawURL: option.URL,
|
||||
interval: interval,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go lb.loop()
|
||||
return lb, nil
|
||||
}
|
@ -12,7 +12,7 @@ type Reject struct {
|
||||
*Base
|
||||
}
|
||||
|
||||
func (r *Reject) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
func (r *Reject) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
return &NopConn{}, nil
|
||||
}
|
||||
|
||||
|
@ -4,15 +4,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"sort"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type Selector struct {
|
||||
*Base
|
||||
selected C.Proxy
|
||||
proxies map[string]C.Proxy
|
||||
selected C.Proxy
|
||||
proxies map[string]C.Proxy
|
||||
proxyList []string
|
||||
}
|
||||
|
||||
type SelectorOption struct {
|
||||
@ -20,20 +20,23 @@ type SelectorOption struct {
|
||||
Proxies []string `proxy:"proxies"`
|
||||
}
|
||||
|
||||
func (s *Selector) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
return s.selected.Generator(metadata)
|
||||
func (s *Selector) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
return s.selected.Dial(metadata)
|
||||
}
|
||||
|
||||
func (s *Selector) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
return s.selected.DialUDP(metadata)
|
||||
}
|
||||
|
||||
func (s *Selector) SupportUDP() bool {
|
||||
return s.selected.SupportUDP()
|
||||
}
|
||||
|
||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for k := range s.proxies {
|
||||
all = append(all, k)
|
||||
}
|
||||
sort.Strings(all)
|
||||
return json.Marshal(map[string]interface{}{
|
||||
"type": s.Type().String(),
|
||||
"now": s.Now(),
|
||||
"all": all,
|
||||
"all": s.proxyList,
|
||||
})
|
||||
}
|
||||
|
||||
@ -56,8 +59,10 @@ func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
||||
}
|
||||
|
||||
mapping := make(map[string]C.Proxy)
|
||||
for _, proxy := range proxies {
|
||||
proxyList := make([]string, len(proxies))
|
||||
for idx, proxy := range proxies {
|
||||
mapping[proxy.Name()] = proxy
|
||||
proxyList[idx] = proxy.Name()
|
||||
}
|
||||
|
||||
s := &Selector{
|
||||
@ -65,8 +70,9 @@ func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
||||
name: name,
|
||||
tp: C.Selector,
|
||||
},
|
||||
proxies: mapping,
|
||||
selected: proxies[0],
|
||||
proxies: mapping,
|
||||
selected: proxies[0],
|
||||
proxyList: proxyList,
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
@ -1,20 +1,20 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
obfs "github.com/Dreamacro/clash/component/simple-obfs"
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
v2rayObfs "github.com/Dreamacro/clash/component/v2ray-plugin"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
type ShadowSocks struct {
|
||||
@ -34,6 +34,7 @@ type ShadowSocksOption struct {
|
||||
Port int `proxy:"port"`
|
||||
Password string `proxy:"password"`
|
||||
Cipher string `proxy:"cipher"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Plugin string `proxy:"plugin,omitempty"`
|
||||
PluginOpts map[string]interface{} `proxy:"plugin-opts,omitempty"`
|
||||
|
||||
@ -48,15 +49,16 @@ type simpleObfsOption struct {
|
||||
}
|
||||
|
||||
type v2rayObfsOption struct {
|
||||
Mode string `obfs:"mode"`
|
||||
Host string `obfs:"host,omitempty"`
|
||||
Path string `obfs:"path,omitempty"`
|
||||
TLS bool `obfs:"tls,omitempty"`
|
||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||
Mode string `obfs:"mode"`
|
||||
Host string `obfs:"host,omitempty"`
|
||||
Path string `obfs:"path,omitempty"`
|
||||
TLS bool `obfs:"tls,omitempty"`
|
||||
Headers map[string]string `obfs:"headers,omitempty"`
|
||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
|
||||
func (ss *ShadowSocks) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := dialTimeout("tcp", ss.server, tcpTimeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %s", ss.server, err.Error())
|
||||
}
|
||||
@ -79,6 +81,26 @@ func (ss *ShadowSocks) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
return c, err
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
pc, err := net.ListenPacket("udp", "")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
addr, err := resolveUDPAddr("udp", ss.server)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
remoteAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(metadata.String(), metadata.DstPort))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
pc = ss.cipher.PacketConn(pc)
|
||||
return &ssUDPConn{PacketConn: pc, rAddr: remoteAddr}, addr, nil
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(map[string]string{
|
||||
"type": ss.Type().String(),
|
||||
@ -115,6 +137,10 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize obfs error: %s", server, err.Error())
|
||||
}
|
||||
|
||||
if opts.Mode != "tls" && opts.Mode != "http" {
|
||||
return nil, fmt.Errorf("ss %s obfs mode error: %s", server, opts.Mode)
|
||||
}
|
||||
obfsMode = opts.Mode
|
||||
obfsOption = &opts
|
||||
} else if option.Plugin == "v2ray-plugin" {
|
||||
@ -122,7 +148,12 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %s", server, err.Error())
|
||||
}
|
||||
|
||||
if opts.Mode != "websocket" {
|
||||
return nil, fmt.Errorf("ss %s obfs mode error: %s", server, opts.Mode)
|
||||
}
|
||||
obfsMode = opts.Mode
|
||||
|
||||
var tlsConfig *tls.Config
|
||||
if opts.TLS {
|
||||
tlsConfig = &tls.Config{
|
||||
@ -131,10 +162,10 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
ClientSessionCache: getClientSessionCache(),
|
||||
}
|
||||
}
|
||||
|
||||
wsOption = &v2rayObfs.WebsocketOption{
|
||||
Host: opts.Host,
|
||||
Path: opts.Path,
|
||||
Headers: opts.Headers,
|
||||
TLSConfig: tlsConfig,
|
||||
}
|
||||
}
|
||||
@ -143,6 +174,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Shadowsocks,
|
||||
udp: option.UDP,
|
||||
},
|
||||
server: server,
|
||||
cipher: ciph,
|
||||
@ -153,22 +185,23 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
}, 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)
|
||||
type ssUDPConn struct {
|
||||
net.PacketConn
|
||||
rAddr net.Addr
|
||||
}
|
||||
|
||||
func (uc *ssUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||
rAddr := socks5.ParseAddr(uc.rAddr.String())
|
||||
copy(buf[len(rAddr):], b)
|
||||
copy(buf, rAddr)
|
||||
return uc.PacketConn.WriteTo(buf[:len(rAddr)+len(b)], addr)
|
||||
}
|
||||
|
||||
func (uc *ssUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, a, e := uc.PacketConn.ReadFrom(b)
|
||||
addr := socks5.SplitAddr(b[:n])
|
||||
copy(b, b[len(addr):])
|
||||
return n - len(addr), a, e
|
||||
}
|
||||
|
@ -1,17 +1,13 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
type Socks5 struct {
|
||||
@ -31,11 +27,12 @@ type Socks5Option struct {
|
||||
UserName string `proxy:"username,omitempty"`
|
||||
Password string `proxy:"password,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
}
|
||||
|
||||
func (ss *Socks5) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := net.DialTimeout("tcp", ss.addr, tcpTimeout)
|
||||
func (ss *Socks5) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := dialTimeout("tcp", ss.addr, tcpTimeout)
|
||||
|
||||
if err == nil && ss.tls {
|
||||
cc := tls.Client(c, ss.tlsConfig)
|
||||
@ -47,69 +44,44 @@ func (ss *Socks5) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
return nil, fmt.Errorf("%s connect error", ss.addr)
|
||||
}
|
||||
tcpKeepAlive(c)
|
||||
if err := ss.shakeHand(metadata, c); err != nil {
|
||||
var user *socks5.User
|
||||
if ss.user != "" {
|
||||
user = &socks5.User{
|
||||
Username: ss.user,
|
||||
Password: ss.pass,
|
||||
}
|
||||
}
|
||||
if err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||
buf := make([]byte, socks.MaxAddrLen)
|
||||
var err error
|
||||
func (ss *Socks5) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
c, err := dialTimeout("tcp", ss.addr, tcpTimeout)
|
||||
|
||||
// VER, NMETHODS, METHODS
|
||||
if len(ss.user) > 0 {
|
||||
_, err = rw.Write([]byte{5, 1, 2})
|
||||
} else {
|
||||
_, err = rw.Write([]byte{5, 1, 0})
|
||||
if err == nil && ss.tls {
|
||||
cc := tls.Client(c, ss.tlsConfig)
|
||||
err = cc.Handshake()
|
||||
c = cc
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, nil, fmt.Errorf("%s connect error", ss.addr)
|
||||
}
|
||||
|
||||
// VER, METHOD
|
||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if buf[0] != 5 {
|
||||
return errors.New("SOCKS version error")
|
||||
}
|
||||
|
||||
if buf[1] == 2 {
|
||||
// password protocol version
|
||||
authMsg := &bytes.Buffer{}
|
||||
authMsg.WriteByte(1)
|
||||
authMsg.WriteByte(uint8(len(ss.user)))
|
||||
authMsg.WriteString(ss.user)
|
||||
authMsg.WriteByte(uint8(len(ss.pass)))
|
||||
authMsg.WriteString(ss.pass)
|
||||
|
||||
if _, err := rw.Write(authMsg.Bytes()); err != nil {
|
||||
return err
|
||||
tcpKeepAlive(c)
|
||||
var user *socks5.User
|
||||
if ss.user != "" {
|
||||
user = &socks5.User{
|
||||
Username: ss.user,
|
||||
Password: ss.pass,
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if buf[1] != 0 {
|
||||
return errors.New("rejected username/password")
|
||||
}
|
||||
} else if buf[1] != 0 {
|
||||
return errors.New("SOCKS need auth")
|
||||
}
|
||||
|
||||
// VER, CMD, RSV, ADDR
|
||||
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
|
||||
return err
|
||||
if err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
return &fakeUDPConn{Conn: c}, c.LocalAddr(), nil
|
||||
}
|
||||
|
||||
func NewSocks5(option Socks5Option) *Socks5 {
|
||||
@ -118,8 +90,6 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
||||
tlsConfig = &tls.Config{
|
||||
InsecureSkipVerify: option.SkipCertVerify,
|
||||
ClientSessionCache: getClientSessionCache(),
|
||||
MinVersion: tls.VersionTLS11,
|
||||
MaxVersion: tls.VersionTLS12,
|
||||
ServerName: option.Server,
|
||||
}
|
||||
}
|
||||
@ -128,6 +98,7 @@ func NewSocks5(option Socks5Option) *Socks5 {
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Socks5,
|
||||
udp: option.UDP,
|
||||
},
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
user: option.UserName,
|
||||
|
@ -1,14 +1,15 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/picker"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
@ -33,20 +34,27 @@ func (u *URLTest) Now() string {
|
||||
return u.fast.Name()
|
||||
}
|
||||
|
||||
func (u *URLTest) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
a, err := u.fast.Generator(metadata)
|
||||
func (u *URLTest) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
a, err := u.fast.Dial(metadata)
|
||||
if err != nil {
|
||||
go u.speedTest()
|
||||
u.fallback()
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
func (u *URLTest) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
return u.fast.DialUDP(metadata)
|
||||
}
|
||||
|
||||
func (u *URLTest) SupportUDP() bool {
|
||||
return u.fast.SupportUDP()
|
||||
}
|
||||
|
||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||
var all []string
|
||||
for _, proxy := range u.proxies {
|
||||
all = append(all, proxy.Name())
|
||||
}
|
||||
sort.Strings(all)
|
||||
return json.Marshal(map[string]interface{}{
|
||||
"type": u.Type().String(),
|
||||
"now": u.Now(),
|
||||
@ -54,7 +62,7 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (u *URLTest) Close() {
|
||||
func (u *URLTest) Destroy() {
|
||||
u.done <- struct{}{}
|
||||
}
|
||||
|
||||
@ -72,8 +80,25 @@ Loop:
|
||||
}
|
||||
}
|
||||
|
||||
func (u *URLTest) fallback() {
|
||||
fast := u.proxies[0]
|
||||
min := fast.LastDelay()
|
||||
for _, proxy := range u.proxies[1:] {
|
||||
if !proxy.Alive() {
|
||||
continue
|
||||
}
|
||||
|
||||
delay := proxy.LastDelay()
|
||||
if delay < min {
|
||||
fast = proxy
|
||||
min = delay
|
||||
}
|
||||
}
|
||||
u.fast = fast
|
||||
}
|
||||
|
||||
func (u *URLTest) speedTest() {
|
||||
if atomic.AddInt32(&u.once, 1) != 1 {
|
||||
if !atomic.CompareAndSwapInt32(&u.once, 0, 1) {
|
||||
return
|
||||
}
|
||||
defer atomic.StoreInt32(&u.once, 0)
|
||||
@ -81,12 +106,12 @@ func (u *URLTest) speedTest() {
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(u.proxies))
|
||||
c := make(chan interface{})
|
||||
fast := selectFast(c)
|
||||
fast := picker.SelectFast(context.Background(), c)
|
||||
timer := time.NewTimer(u.interval)
|
||||
|
||||
for _, p := range u.proxies {
|
||||
go func(p C.Proxy) {
|
||||
_, err := DelayTest(p, u.rawURL)
|
||||
_, err := p.URLTest(u.rawURL)
|
||||
if err == nil {
|
||||
c <- p
|
||||
}
|
||||
|
@ -1,15 +1,18 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/dns"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -21,39 +24,6 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// DelayTest get the delay for the specified URL
|
||||
func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
|
||||
addr, err := urlToMetadata(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
instance, err := proxy.Generator(&addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer instance.Close()
|
||||
transport := &http.Transport{
|
||||
Dial: func(string, string) (net.Conn, error) {
|
||||
return instance, nil
|
||||
},
|
||||
// from http.DefaultTransport
|
||||
MaxIdleConns: 100,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
client := http.Client{Transport: transport}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resp.Body.Close()
|
||||
t = int16(time.Since(start) / time.Millisecond)
|
||||
return
|
||||
}
|
||||
|
||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
@ -75,27 +45,12 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||
addr = C.Metadata{
|
||||
AddrType: C.AtypDomainName,
|
||||
Host: u.Hostname(),
|
||||
IP: nil,
|
||||
Port: port,
|
||||
DstIP: nil,
|
||||
DstPort: port,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func selectFast(in chan interface{}) chan interface{} {
|
||||
out := make(chan interface{})
|
||||
go func() {
|
||||
p, open := <-in
|
||||
if open {
|
||||
out <- p
|
||||
}
|
||||
close(out)
|
||||
for range in {
|
||||
}
|
||||
}()
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func tcpKeepAlive(c net.Conn) {
|
||||
if tcp, ok := c.(*net.TCPConn); ok {
|
||||
tcp.SetKeepAlive(true)
|
||||
@ -109,3 +64,63 @@ func getClientSessionCache() tls.ClientSessionCache {
|
||||
})
|
||||
return globalClientSessionCache
|
||||
}
|
||||
|
||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||
var buf [][]byte
|
||||
aType := uint8(metadata.AddrType)
|
||||
p, _ := strconv.Atoi(metadata.DstPort)
|
||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||
switch metadata.AddrType {
|
||||
case socks5.AtypDomainName:
|
||||
len := uint8(len(metadata.Host))
|
||||
host := []byte(metadata.Host)
|
||||
buf = [][]byte{{aType, len}, host, port}
|
||||
case socks5.AtypIPv4:
|
||||
host := metadata.DstIP.To4()
|
||||
buf = [][]byte{{aType}, host, port}
|
||||
case socks5.AtypIPv6:
|
||||
host := metadata.DstIP.To16()
|
||||
buf = [][]byte{{aType}, host, port}
|
||||
}
|
||||
return bytes.Join(buf, nil)
|
||||
}
|
||||
|
||||
type fakeUDPConn struct {
|
||||
net.Conn
|
||||
}
|
||||
|
||||
func (fuc *fakeUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
return fuc.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (fuc *fakeUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, err := fuc.Conn.Read(b)
|
||||
return n, fuc.RemoteAddr(), err
|
||||
}
|
||||
|
||||
func dialTimeout(network, address string, timeout time.Duration) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ip, err := dns.ResolveIP(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return net.DialTimeout(network, net.JoinHostPort(ip.String(), port), timeout)
|
||||
}
|
||||
|
||||
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ip, err := dns.ResolveIP(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||
}
|
||||
|
@ -24,14 +24,15 @@ type VmessOption struct {
|
||||
AlterID int `proxy:"alterId"`
|
||||
Cipher string `proxy:"cipher"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
WSPath string `proxy:"ws-path,omitempty"`
|
||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
}
|
||||
|
||||
func (v *Vmess) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := net.DialTimeout("tcp", v.server, tcpTimeout)
|
||||
func (v *Vmess) Dial(metadata *C.Metadata) (net.Conn, error) {
|
||||
c, err := dialTimeout("tcp", v.server, tcpTimeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error", v.server)
|
||||
}
|
||||
@ -40,6 +41,16 @@ func (v *Vmess) Generator(metadata *C.Metadata) (net.Conn, error) {
|
||||
return c, err
|
||||
}
|
||||
|
||||
func (v *Vmess) DialUDP(metadata *C.Metadata) (net.PacketConn, net.Addr, error) {
|
||||
c, err := dialTimeout("tcp", v.server, tcpTimeout)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("%s connect error", v.server)
|
||||
}
|
||||
tcpKeepAlive(c)
|
||||
c, err = v.client.New(c, parseVmessAddr(metadata))
|
||||
return &fakeUDPConn{Conn: c}, c.LocalAddr(), err
|
||||
}
|
||||
|
||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
security := strings.ToLower(option.Cipher)
|
||||
client, err := vmess.NewClient(vmess.Config{
|
||||
@ -63,6 +74,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
Base: &Base{
|
||||
name: option.Name,
|
||||
tp: C.Vmess,
|
||||
udp: option.UDP,
|
||||
},
|
||||
server: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
client: client,
|
||||
@ -76,11 +88,11 @@ func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||
case C.AtypIPv4:
|
||||
addrType = byte(vmess.AtypIPv4)
|
||||
addr = make([]byte, net.IPv4len)
|
||||
copy(addr[:], metadata.IP.To4())
|
||||
copy(addr[:], metadata.DstIP.To4())
|
||||
case C.AtypIPv6:
|
||||
addrType = byte(vmess.AtypIPv6)
|
||||
addr = make([]byte, net.IPv6len)
|
||||
copy(addr[:], metadata.IP.To16())
|
||||
copy(addr[:], metadata.DstIP.To16())
|
||||
case C.AtypDomainName:
|
||||
addrType = byte(vmess.AtypDomainName)
|
||||
addr = make([]byte, len(metadata.Host)+1)
|
||||
@ -88,8 +100,9 @@ func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||
copy(addr[1:], []byte(metadata.Host))
|
||||
}
|
||||
|
||||
port, _ := strconv.Atoi(metadata.Port)
|
||||
port, _ := strconv.Atoi(metadata.DstPort)
|
||||
return &vmess.DstAddr{
|
||||
UDP: metadata.NetWork == C.UDP,
|
||||
AddrType: addrType,
|
||||
Addr: addr,
|
||||
Port: uint(port),
|
||||
|
50
common/murmur3/murmur.go
Normal file
50
common/murmur3/murmur.go
Normal file
@ -0,0 +1,50 @@
|
||||
package murmur3
|
||||
|
||||
type bmixer interface {
|
||||
bmix(p []byte) (tail []byte)
|
||||
Size() (n int)
|
||||
reset()
|
||||
}
|
||||
|
||||
type digest struct {
|
||||
clen int // Digested input cumulative length.
|
||||
tail []byte // 0 to Size()-1 bytes view of `buf'.
|
||||
buf [16]byte // Expected (but not required) to be Size() large.
|
||||
seed uint32 // Seed for initializing the hash.
|
||||
bmixer
|
||||
}
|
||||
|
||||
func (d *digest) BlockSize() int { return 1 }
|
||||
|
||||
func (d *digest) Write(p []byte) (n int, err error) {
|
||||
n = len(p)
|
||||
d.clen += n
|
||||
|
||||
if len(d.tail) > 0 {
|
||||
// Stick back pending bytes.
|
||||
nfree := d.Size() - len(d.tail) // nfree ∈ [1, d.Size()-1].
|
||||
if nfree < len(p) {
|
||||
// One full block can be formed.
|
||||
block := append(d.tail, p[:nfree]...)
|
||||
p = p[nfree:]
|
||||
_ = d.bmix(block) // No tail.
|
||||
} else {
|
||||
// Tail's buf is large enough to prevent reallocs.
|
||||
p = append(d.tail, p...)
|
||||
}
|
||||
}
|
||||
|
||||
d.tail = d.bmix(p)
|
||||
|
||||
// Keep own copy of the 0 to Size()-1 pending bytes.
|
||||
nn := copy(d.buf[:], d.tail)
|
||||
d.tail = d.buf[:nn]
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (d *digest) Reset() {
|
||||
d.clen = 0
|
||||
d.tail = nil
|
||||
d.bmixer.reset()
|
||||
}
|
145
common/murmur3/murmur32.go
Normal file
145
common/murmur3/murmur32.go
Normal file
@ -0,0 +1,145 @@
|
||||
package murmur3
|
||||
|
||||
// https://github.com/spaolacci/murmur3/blob/master/murmur32.go
|
||||
|
||||
import (
|
||||
"hash"
|
||||
"math/bits"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Make sure interfaces are correctly implemented.
|
||||
var (
|
||||
_ hash.Hash32 = new(digest32)
|
||||
_ bmixer = new(digest32)
|
||||
)
|
||||
|
||||
const (
|
||||
c1_32 uint32 = 0xcc9e2d51
|
||||
c2_32 uint32 = 0x1b873593
|
||||
)
|
||||
|
||||
// digest32 represents a partial evaluation of a 32 bites hash.
|
||||
type digest32 struct {
|
||||
digest
|
||||
h1 uint32 // Unfinalized running hash.
|
||||
}
|
||||
|
||||
// New32 returns new 32-bit hasher
|
||||
func New32() hash.Hash32 { return New32WithSeed(0) }
|
||||
|
||||
// New32WithSeed returns new 32-bit hasher set with explicit seed value
|
||||
func New32WithSeed(seed uint32) hash.Hash32 {
|
||||
d := new(digest32)
|
||||
d.seed = seed
|
||||
d.bmixer = d
|
||||
d.Reset()
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *digest32) Size() int { return 4 }
|
||||
|
||||
func (d *digest32) reset() { d.h1 = d.seed }
|
||||
|
||||
func (d *digest32) Sum(b []byte) []byte {
|
||||
h := d.Sum32()
|
||||
return append(b, byte(h>>24), byte(h>>16), byte(h>>8), byte(h))
|
||||
}
|
||||
|
||||
// Digest as many blocks as possible.
|
||||
func (d *digest32) bmix(p []byte) (tail []byte) {
|
||||
h1 := d.h1
|
||||
|
||||
nblocks := len(p) / 4
|
||||
for i := 0; i < nblocks; i++ {
|
||||
k1 := *(*uint32)(unsafe.Pointer(&p[i*4]))
|
||||
|
||||
k1 *= c1_32
|
||||
k1 = bits.RotateLeft32(k1, 15)
|
||||
k1 *= c2_32
|
||||
|
||||
h1 ^= k1
|
||||
h1 = bits.RotateLeft32(h1, 13)
|
||||
h1 = h1*4 + h1 + 0xe6546b64
|
||||
}
|
||||
d.h1 = h1
|
||||
return p[nblocks*d.Size():]
|
||||
}
|
||||
|
||||
func (d *digest32) Sum32() (h1 uint32) {
|
||||
|
||||
h1 = d.h1
|
||||
|
||||
var k1 uint32
|
||||
switch len(d.tail) & 3 {
|
||||
case 3:
|
||||
k1 ^= uint32(d.tail[2]) << 16
|
||||
fallthrough
|
||||
case 2:
|
||||
k1 ^= uint32(d.tail[1]) << 8
|
||||
fallthrough
|
||||
case 1:
|
||||
k1 ^= uint32(d.tail[0])
|
||||
k1 *= c1_32
|
||||
k1 = bits.RotateLeft32(k1, 15)
|
||||
k1 *= c2_32
|
||||
h1 ^= k1
|
||||
}
|
||||
|
||||
h1 ^= uint32(d.clen)
|
||||
|
||||
h1 ^= h1 >> 16
|
||||
h1 *= 0x85ebca6b
|
||||
h1 ^= h1 >> 13
|
||||
h1 *= 0xc2b2ae35
|
||||
h1 ^= h1 >> 16
|
||||
|
||||
return h1
|
||||
}
|
||||
|
||||
func Sum32(data []byte) uint32 { return Sum32WithSeed(data, 0) }
|
||||
|
||||
func Sum32WithSeed(data []byte, seed uint32) uint32 {
|
||||
h1 := seed
|
||||
|
||||
nblocks := len(data) / 4
|
||||
for i := 0; i < nblocks; i++ {
|
||||
k1 := *(*uint32)(unsafe.Pointer(&data[i*4]))
|
||||
|
||||
k1 *= c1_32
|
||||
k1 = bits.RotateLeft32(k1, 15)
|
||||
k1 *= c2_32
|
||||
|
||||
h1 ^= k1
|
||||
h1 = bits.RotateLeft32(h1, 13)
|
||||
h1 = h1*4 + h1 + 0xe6546b64
|
||||
}
|
||||
|
||||
tail := data[nblocks*4:]
|
||||
|
||||
var k1 uint32
|
||||
switch len(tail) & 3 {
|
||||
case 3:
|
||||
k1 ^= uint32(tail[2]) << 16
|
||||
fallthrough
|
||||
case 2:
|
||||
k1 ^= uint32(tail[1]) << 8
|
||||
fallthrough
|
||||
case 1:
|
||||
k1 ^= uint32(tail[0])
|
||||
k1 *= c1_32
|
||||
k1 = bits.RotateLeft32(k1, 15)
|
||||
k1 *= c2_32
|
||||
h1 ^= k1
|
||||
}
|
||||
|
||||
h1 ^= uint32(len(data))
|
||||
|
||||
h1 ^= h1 >> 16
|
||||
h1 *= 0x85ebca6b
|
||||
h1 ^= h1 >> 13
|
||||
h1 *= 0xc2b2ae35
|
||||
h1 ^= h1 >> 16
|
||||
|
||||
return h1
|
||||
}
|
15
common/pool/pool.go
Normal file
15
common/pool/pool.go
Normal file
@ -0,0 +1,15 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// io.Copy default buffer size is 32 KiB
|
||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||
bufferSize = 20 * 1024
|
||||
)
|
||||
|
||||
// BufPool provide buffer for relay
|
||||
var BufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
|
71
common/queue/queue.go
Normal file
71
common/queue/queue.go
Normal file
@ -0,0 +1,71 @@
|
||||
package queue
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Queue is a simple concurrent safe queue
|
||||
type Queue struct {
|
||||
items []interface{}
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// Put add the item to the queue.
|
||||
func (q *Queue) Put(items ...interface{}) {
|
||||
if len(items) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
q.lock.Lock()
|
||||
q.items = append(q.items, items...)
|
||||
q.lock.Unlock()
|
||||
}
|
||||
|
||||
// Pop returns the head of items.
|
||||
func (q *Queue) Pop() interface{} {
|
||||
if len(q.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
q.lock.Lock()
|
||||
head := q.items[0]
|
||||
q.items = q.items[1:]
|
||||
q.lock.Unlock()
|
||||
return head
|
||||
}
|
||||
|
||||
// First returns the head of items without deleting.
|
||||
func (q *Queue) First() interface{} {
|
||||
if len(q.items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
q.lock.RLock()
|
||||
head := q.items[0]
|
||||
q.lock.RUnlock()
|
||||
return head
|
||||
}
|
||||
|
||||
// Copy get the copy of queue.
|
||||
func (q *Queue) Copy() []interface{} {
|
||||
items := []interface{}{}
|
||||
q.lock.RLock()
|
||||
items = append(items, q.items...)
|
||||
q.lock.RUnlock()
|
||||
return items
|
||||
}
|
||||
|
||||
// Len returns the number of items in this queue.
|
||||
func (q *Queue) Len() int64 {
|
||||
q.lock.Lock()
|
||||
defer q.lock.Unlock()
|
||||
|
||||
return int64(len(q.items))
|
||||
}
|
||||
|
||||
// New is a constructor for a new concurrent safe queue.
|
||||
func New(hint int64) *Queue {
|
||||
return &Queue{
|
||||
items: make([]interface{}, 0, hint),
|
||||
}
|
||||
}
|
@ -47,11 +47,11 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
|
||||
}
|
||||
|
||||
value, ok := src[key]
|
||||
if !ok {
|
||||
if !ok || value == nil {
|
||||
if omitempty {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("key %s missing", key)
|
||||
return fmt.Errorf("key '%s' missing", key)
|
||||
}
|
||||
|
||||
err := d.decode(key, value, v.Field(idx))
|
||||
@ -114,7 +114,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value)
|
||||
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
||||
default:
|
||||
err = fmt.Errorf(
|
||||
"'%s' expected type'%s', got unconvertible type '%s'",
|
||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||
name, val.Type(), dataVal.Type(),
|
||||
)
|
||||
}
|
||||
@ -131,7 +131,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (
|
||||
val.SetBool(dataVal.Int() != 0)
|
||||
default:
|
||||
err = fmt.Errorf(
|
||||
"'%s' expected type'%s', got unconvertible type '%s'",
|
||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||
name, val.Type(), dataVal.Type(),
|
||||
)
|
||||
}
|
||||
|
46
component/auth/auth.go
Normal file
46
component/auth/auth.go
Normal file
@ -0,0 +1,46 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Authenticator interface {
|
||||
Verify(user string, pass string) bool
|
||||
Users() []string
|
||||
}
|
||||
|
||||
type AuthUser struct {
|
||||
User string
|
||||
Pass string
|
||||
}
|
||||
|
||||
type inMemoryAuthenticator struct {
|
||||
storage *sync.Map
|
||||
usernames []string
|
||||
}
|
||||
|
||||
func (au *inMemoryAuthenticator) Verify(user string, pass string) bool {
|
||||
realPass, ok := au.storage.Load(user)
|
||||
return ok && realPass == pass
|
||||
}
|
||||
|
||||
func (au *inMemoryAuthenticator) Users() []string { return au.usernames }
|
||||
|
||||
func NewAuthenticator(users []AuthUser) Authenticator {
|
||||
if len(users) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
au := &inMemoryAuthenticator{storage: &sync.Map{}}
|
||||
for _, user := range users {
|
||||
au.storage.Store(user.User, user.Pass)
|
||||
}
|
||||
usernames := make([]string, 0, len(users))
|
||||
au.storage.Range(func(key, value interface{}) bool {
|
||||
usernames = append(usernames, key.(string))
|
||||
return true
|
||||
})
|
||||
au.usernames = usernames
|
||||
|
||||
return au
|
||||
}
|
55
component/fakeip/pool.go
Normal file
55
component/fakeip/pool.go
Normal file
@ -0,0 +1,55 @@
|
||||
package fakeip
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Pool is a implementation about fake ip generator without storage
|
||||
type Pool struct {
|
||||
max uint32
|
||||
min uint32
|
||||
offset uint32
|
||||
mux *sync.Mutex
|
||||
}
|
||||
|
||||
// Get return a new fake ip
|
||||
func (p *Pool) Get() net.IP {
|
||||
p.mux.Lock()
|
||||
defer p.mux.Unlock()
|
||||
ip := uintToIP(p.min + p.offset)
|
||||
p.offset = (p.offset + 1) % (p.max - p.min)
|
||||
return ip
|
||||
}
|
||||
|
||||
func ipToUint(ip net.IP) uint32 {
|
||||
v := uint32(ip[0]) << 24
|
||||
v += uint32(ip[1]) << 16
|
||||
v += uint32(ip[2]) << 8
|
||||
v += uint32(ip[3])
|
||||
return v
|
||||
}
|
||||
|
||||
func uintToIP(v uint32) net.IP {
|
||||
return net.IPv4(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
|
||||
}
|
||||
|
||||
// New return Pool instance
|
||||
func New(ipnet *net.IPNet) (*Pool, error) {
|
||||
min := ipToUint(ipnet.IP) + 1
|
||||
|
||||
ones, bits := ipnet.Mask.Size()
|
||||
total := 1<<uint(bits-ones) - 2
|
||||
|
||||
if total <= 0 {
|
||||
return nil, errors.New("ipnet don't have valid ip")
|
||||
}
|
||||
|
||||
max := min + uint32(total)
|
||||
return &Pool{
|
||||
min: min,
|
||||
max: max,
|
||||
mux: &sync.Mutex{},
|
||||
}, nil
|
||||
}
|
44
component/fakeip/pool_test.go
Normal file
44
component/fakeip/pool_test.go
Normal file
@ -0,0 +1,44 @@
|
||||
package fakeip
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPool_Basic(t *testing.T) {
|
||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/30")
|
||||
pool, _ := New(ipnet)
|
||||
|
||||
first := pool.Get()
|
||||
last := pool.Get()
|
||||
|
||||
if !first.Equal(net.IP{192, 168, 0, 1}) {
|
||||
t.Error("should get right first ip, instead of", first.String())
|
||||
}
|
||||
|
||||
if !last.Equal(net.IP{192, 168, 0, 2}) {
|
||||
t.Error("should get right last ip, instead of", first.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPool_Cycle(t *testing.T) {
|
||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/30")
|
||||
pool, _ := New(ipnet)
|
||||
|
||||
first := pool.Get()
|
||||
pool.Get()
|
||||
same := pool.Get()
|
||||
|
||||
if !first.Equal(same) {
|
||||
t.Error("should return same ip", first.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPool_Error(t *testing.T) {
|
||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/31")
|
||||
_, err := New(ipnet)
|
||||
|
||||
if err == nil {
|
||||
t.Error("should return err")
|
||||
}
|
||||
}
|
@ -8,6 +8,8 @@ import (
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
// HTTPObfs is shadowsocks http simple-obfs implementation
|
||||
@ -32,15 +34,15 @@ func (ho *HTTPObfs) Read(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
if ho.firstResponse {
|
||||
buf := bufPool.Get().([]byte)
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
n, err := ho.Conn.Read(buf)
|
||||
if err != nil {
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.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)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
return 0, io.EOF
|
||||
}
|
||||
ho.firstResponse = false
|
||||
@ -50,7 +52,7 @@ func (ho *HTTPObfs) Read(b []byte) (int, error) {
|
||||
ho.buf = buf[:idx+4+length]
|
||||
ho.offset = idx + 4 + n
|
||||
} else {
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
@ -6,8 +6,9 @@ import (
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@ -18,8 +19,6 @@ const (
|
||||
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
|
||||
)
|
||||
|
||||
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, 2048) }}
|
||||
|
||||
// TLSObfs is shadowsocks tls simple-obfs implementation
|
||||
type TLSObfs struct {
|
||||
net.Conn
|
||||
@ -30,12 +29,12 @@ type TLSObfs struct {
|
||||
}
|
||||
|
||||
func (to *TLSObfs) read(b []byte, discardN int) (int, error) {
|
||||
buf := bufPool.Get().([]byte)
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
_, err := io.ReadFull(to.Conn, buf[:discardN])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
|
||||
sizeBuf := make([]byte, 2)
|
||||
_, err = io.ReadFull(to.Conn, sizeBuf)
|
||||
@ -103,7 +102,7 @@ func (to *TLSObfs) write(b []byte) (int, error) {
|
||||
return len(b), err
|
||||
}
|
||||
|
||||
size := bufPool.Get().([]byte)
|
||||
size := pool.BufPool.Get().([]byte)
|
||||
binary.BigEndian.PutUint16(size[:2], uint16(len(b)))
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
@ -111,7 +110,7 @@ func (to *TLSObfs) write(b []byte) (int, error) {
|
||||
buf.Write(size[:2])
|
||||
buf.Write(b)
|
||||
_, err := to.Conn.Write(buf.Bytes())
|
||||
bufPool.Put(size[:cap(size)])
|
||||
pool.BufPool.Put(size[:cap(size)])
|
||||
return len(b), err
|
||||
}
|
||||
|
||||
|
309
component/socks5/socks5.go
Normal file
309
component/socks5/socks5.go
Normal file
@ -0,0 +1,309 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/component/auth"
|
||||
)
|
||||
|
||||
// Error represents a SOCKS error
|
||||
type Error byte
|
||||
|
||||
func (err Error) Error() string {
|
||||
return "SOCKS error: " + strconv.Itoa(int(err))
|
||||
}
|
||||
|
||||
// Command is request commands as defined in RFC 1928 section 4.
|
||||
type Command = uint8
|
||||
|
||||
// SOCKS request commands as defined in RFC 1928 section 4.
|
||||
const (
|
||||
CmdConnect Command = 1
|
||||
CmdBind Command = 2
|
||||
CmdUDPAssociate Command = 3
|
||||
)
|
||||
|
||||
// SOCKS address types as defined in RFC 1928 section 5.
|
||||
const (
|
||||
AtypIPv4 = 1
|
||||
AtypDomainName = 3
|
||||
AtypIPv6 = 4
|
||||
)
|
||||
|
||||
// MaxAddrLen is the maximum size of SOCKS address in bytes.
|
||||
const MaxAddrLen = 1 + 1 + 255 + 2
|
||||
|
||||
// MaxAuthLen is the maximum size of user/password field in SOCKS5 Auth
|
||||
const MaxAuthLen = 255
|
||||
|
||||
// Addr represents a SOCKS address as defined in RFC 1928 section 5.
|
||||
type Addr = []byte
|
||||
|
||||
// SOCKS errors as defined in RFC 1928 section 6.
|
||||
const (
|
||||
ErrGeneralFailure = Error(1)
|
||||
ErrConnectionNotAllowed = Error(2)
|
||||
ErrNetworkUnreachable = Error(3)
|
||||
ErrHostUnreachable = Error(4)
|
||||
ErrConnectionRefused = Error(5)
|
||||
ErrTTLExpired = Error(6)
|
||||
ErrCommandNotSupported = Error(7)
|
||||
ErrAddressNotSupported = Error(8)
|
||||
)
|
||||
|
||||
// Auth errors used to return a specific "Auth failed" error
|
||||
var ErrAuth = errors.New("auth failed")
|
||||
|
||||
type User struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// ServerHandshake fast-tracks SOCKS initialization to get target address to connect on server side.
|
||||
func ServerHandshake(rw net.Conn, authenticator auth.Authenticator) (addr Addr, command Command, err error) {
|
||||
// Read RFC 1928 for request and reply structure and sizes.
|
||||
buf := make([]byte, MaxAddrLen)
|
||||
// read VER, NMETHODS, METHODS
|
||||
if _, err = io.ReadFull(rw, buf[:2]); err != nil {
|
||||
return
|
||||
}
|
||||
nmethods := buf[1]
|
||||
if _, err = io.ReadFull(rw, buf[:nmethods]); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// write VER METHOD
|
||||
if authenticator != nil {
|
||||
if _, err = rw.Write([]byte{5, 2}); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Get header
|
||||
header := make([]byte, 2)
|
||||
if _, err = io.ReadFull(rw, header); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
authBuf := make([]byte, MaxAuthLen)
|
||||
// Get username
|
||||
userLen := int(header[1])
|
||||
if userLen <= 0 {
|
||||
rw.Write([]byte{1, 1})
|
||||
err = ErrAuth
|
||||
return
|
||||
}
|
||||
if _, err = io.ReadFull(rw, authBuf[:userLen]); err != nil {
|
||||
return
|
||||
}
|
||||
user := string(authBuf[:userLen])
|
||||
|
||||
// Get password
|
||||
if _, err = rw.Read(header[:1]); err != nil {
|
||||
return
|
||||
}
|
||||
passLen := int(header[0])
|
||||
if passLen <= 0 {
|
||||
rw.Write([]byte{1, 1})
|
||||
err = ErrAuth
|
||||
return
|
||||
}
|
||||
if _, err = io.ReadFull(rw, authBuf[:passLen]); err != nil {
|
||||
return
|
||||
}
|
||||
pass := string(authBuf[:passLen])
|
||||
|
||||
// Verify
|
||||
if ok := authenticator.Verify(string(user), string(pass)); !ok {
|
||||
rw.Write([]byte{1, 1})
|
||||
err = ErrAuth
|
||||
return
|
||||
}
|
||||
|
||||
// Response auth state
|
||||
if _, err = rw.Write([]byte{1, 0}); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if _, err = rw.Write([]byte{5, 0}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// read VER CMD RSV ATYP DST.ADDR DST.PORT
|
||||
if _, err = io.ReadFull(rw, buf[:3]); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if buf[1] != CmdConnect && buf[1] != CmdUDPAssociate {
|
||||
err = ErrCommandNotSupported
|
||||
return
|
||||
}
|
||||
|
||||
command = buf[1]
|
||||
addr, err = readAddr(rw, buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// write VER REP RSV ATYP BND.ADDR BND.PORT
|
||||
_, err = rw.Write([]byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0})
|
||||
return
|
||||
}
|
||||
|
||||
// ClientHandshake fast-tracks SOCKS initialization to get target address to connect on client side.
|
||||
func ClientHandshake(rw io.ReadWriter, addr Addr, cammand Command, user *User) error {
|
||||
buf := make([]byte, MaxAddrLen)
|
||||
var err error
|
||||
|
||||
// VER, NMETHODS, METHODS
|
||||
if user != nil {
|
||||
_, err = rw.Write([]byte{5, 1, 2})
|
||||
} else {
|
||||
_, err = rw.Write([]byte{5, 1, 0})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// VER, METHOD
|
||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if buf[0] != 5 {
|
||||
return errors.New("SOCKS version error")
|
||||
}
|
||||
|
||||
if buf[1] == 2 {
|
||||
// password protocol version
|
||||
authMsg := &bytes.Buffer{}
|
||||
authMsg.WriteByte(1)
|
||||
authMsg.WriteByte(uint8(len(user.Username)))
|
||||
authMsg.WriteString(user.Username)
|
||||
authMsg.WriteByte(uint8(len(user.Password)))
|
||||
authMsg.WriteString(user.Password)
|
||||
|
||||
if _, err := rw.Write(authMsg.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if buf[1] != 0 {
|
||||
return errors.New("rejected username/password")
|
||||
}
|
||||
} else if buf[1] != 0 {
|
||||
return errors.New("SOCKS need auth")
|
||||
}
|
||||
|
||||
// VER, CMD, RSV, ADDR
|
||||
if _, err := rw.Write(bytes.Join([][]byte{{5, cammand, 0}, addr}, []byte(""))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readAddr(r io.Reader, b []byte) (Addr, error) {
|
||||
if len(b) < MaxAddrLen {
|
||||
return nil, io.ErrShortBuffer
|
||||
}
|
||||
_, err := io.ReadFull(r, b[:1]) // read 1st byte for address type
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch b[0] {
|
||||
case AtypDomainName:
|
||||
_, err = io.ReadFull(r, b[1:2]) // read 2nd byte for domain length
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
domainLength := uint16(b[1])
|
||||
_, err = io.ReadFull(r, b[2:2+domainLength+2])
|
||||
return b[:1+1+domainLength+2], err
|
||||
case AtypIPv4:
|
||||
_, err = io.ReadFull(r, b[1:1+net.IPv4len+2])
|
||||
return b[:1+net.IPv4len+2], err
|
||||
case AtypIPv6:
|
||||
_, err = io.ReadFull(r, b[1:1+net.IPv6len+2])
|
||||
return b[:1+net.IPv6len+2], err
|
||||
}
|
||||
|
||||
return nil, ErrAddressNotSupported
|
||||
}
|
||||
|
||||
// SplitAddr slices a SOCKS address from beginning of b. Returns nil if failed.
|
||||
func SplitAddr(b []byte) Addr {
|
||||
addrLen := 1
|
||||
if len(b) < addrLen {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch b[0] {
|
||||
case AtypDomainName:
|
||||
if len(b) < 2 {
|
||||
return nil
|
||||
}
|
||||
addrLen = 1 + 1 + int(b[1]) + 2
|
||||
case AtypIPv4:
|
||||
addrLen = 1 + net.IPv4len + 2
|
||||
case AtypIPv6:
|
||||
addrLen = 1 + net.IPv6len + 2
|
||||
default:
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
if len(b) < addrLen {
|
||||
return nil
|
||||
}
|
||||
|
||||
return b[:addrLen]
|
||||
}
|
||||
|
||||
// ParseAddr parses the address in string s. Returns nil if failed.
|
||||
func ParseAddr(s string) Addr {
|
||||
var addr Addr
|
||||
host, port, err := net.SplitHostPort(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
addr = make([]byte, 1+net.IPv4len+2)
|
||||
addr[0] = AtypIPv4
|
||||
copy(addr[1:], ip4)
|
||||
} else {
|
||||
addr = make([]byte, 1+net.IPv6len+2)
|
||||
addr[0] = AtypIPv6
|
||||
copy(addr[1:], ip)
|
||||
}
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
return nil
|
||||
}
|
||||
addr = make([]byte, 1+1+len(host)+2)
|
||||
addr[0] = AtypDomainName
|
||||
addr[1] = byte(len(host))
|
||||
copy(addr[2:], host)
|
||||
}
|
||||
|
||||
portnum, err := strconv.ParseUint(port, 10, 16)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
addr[len(addr)-2], addr[len(addr)-1] = byte(portnum>>8), byte(portnum)
|
||||
|
||||
return addr
|
||||
}
|
@ -11,6 +11,7 @@ import (
|
||||
type WebsocketOption struct {
|
||||
Host string
|
||||
Path string
|
||||
Headers map[string]string
|
||||
TLSConfig *tls.Config
|
||||
}
|
||||
|
||||
@ -20,6 +21,7 @@ func NewWebsocketObfs(conn net.Conn, option *WebsocketOption) (net.Conn, error)
|
||||
Host: option.Host,
|
||||
Path: option.Path,
|
||||
TLS: option.TLSConfig != nil,
|
||||
Headers: option.Headers,
|
||||
TLSConfig: option.TLSConfig,
|
||||
}
|
||||
|
||||
|
@ -5,6 +5,8 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
type aeadWriter struct {
|
||||
@ -20,8 +22,8 @@ func newAEADWriter(w io.Writer, aead cipher.AEAD, iv []byte) *aeadWriter {
|
||||
}
|
||||
|
||||
func (w *aeadWriter) Write(b []byte) (n int, err error) {
|
||||
buf := bufPool.Get().([]byte)
|
||||
defer bufPool.Put(buf[:cap(buf)])
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||
length := len(b)
|
||||
for {
|
||||
if length == 0 {
|
||||
@ -71,7 +73,7 @@ func (r *aeadReader) Read(b []byte) (int, error) {
|
||||
n := copy(b, r.buf[r.offset:])
|
||||
r.offset += n
|
||||
if r.offset == len(r.buf) {
|
||||
bufPool.Put(r.buf[:cap(r.buf)])
|
||||
pool.BufPool.Put(r.buf[:cap(r.buf)])
|
||||
r.buf = nil
|
||||
}
|
||||
return n, nil
|
||||
@ -87,10 +89,10 @@ func (r *aeadReader) Read(b []byte) (int, error) {
|
||||
return 0, errors.New("Buffer is larger than standard")
|
||||
}
|
||||
|
||||
buf := bufPool.Get().([]byte)
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
_, err = io.ReadFull(r.Reader, buf[:size])
|
||||
if err != nil {
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@ -105,7 +107,7 @@ func (r *aeadReader) Read(b []byte) (int, error) {
|
||||
realLen := size - r.Overhead()
|
||||
n := copy(b, buf[:realLen])
|
||||
if len(b) >= realLen {
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
return n, nil
|
||||
}
|
||||
|
||||
|
@ -4,7 +4,8 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -13,8 +14,6 @@ const (
|
||||
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
|
||||
@ -35,7 +34,7 @@ func (cr *chunkReader) Read(b []byte) (int, error) {
|
||||
n := copy(b, cr.buf[cr.offset:])
|
||||
cr.offset += n
|
||||
if cr.offset == len(cr.buf) {
|
||||
bufPool.Put(cr.buf[:cap(cr.buf)])
|
||||
pool.BufPool.Put(cr.buf[:cap(cr.buf)])
|
||||
cr.buf = nil
|
||||
}
|
||||
return n, nil
|
||||
@ -60,10 +59,10 @@ func (cr *chunkReader) Read(b []byte) (int, error) {
|
||||
return size, nil
|
||||
}
|
||||
|
||||
buf := bufPool.Get().([]byte)
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
_, err = io.ReadFull(cr.Reader, buf[:size])
|
||||
if err != nil {
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
return 0, err
|
||||
}
|
||||
n := copy(b, cr.buf[:])
|
||||
@ -77,8 +76,8 @@ type chunkWriter struct {
|
||||
}
|
||||
|
||||
func (cw *chunkWriter) Write(b []byte) (n int, err error) {
|
||||
buf := bufPool.Get().([]byte)
|
||||
defer bufPool.Put(buf[:cap(buf)])
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||
length := len(b)
|
||||
for {
|
||||
if length == 0 {
|
||||
|
@ -35,20 +35,10 @@ type Conn struct {
|
||||
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)
|
||||
}
|
||||
|
||||
@ -87,7 +77,11 @@ func (vc *Conn) sendRequest() error {
|
||||
// P Sec Reserve Cmd
|
||||
buf.WriteByte(byte(p<<4) | byte(vc.security))
|
||||
buf.WriteByte(0)
|
||||
buf.WriteByte(CommandTCP)
|
||||
if vc.dst.UDP {
|
||||
buf.WriteByte(CommandUDP)
|
||||
} else {
|
||||
buf.WriteByte(CommandTCP)
|
||||
}
|
||||
|
||||
// Port AddrType Addr
|
||||
binary.Write(buf, binary.BigEndian, uint16(vc.dst.Port))
|
||||
@ -153,7 +147,7 @@ func hashTimestamp(t time.Time) []byte {
|
||||
}
|
||||
|
||||
// newConn return a Conn instance
|
||||
func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
||||
func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) (*Conn, error) {
|
||||
randBytes := make([]byte, 33)
|
||||
rand.Read(randBytes)
|
||||
reqBodyIV := make([]byte, 16)
|
||||
@ -196,7 +190,7 @@ func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
||||
reader = newAEADReader(conn, aead, respBodyIV[:])
|
||||
}
|
||||
|
||||
return &Conn{
|
||||
c := &Conn{
|
||||
Conn: conn,
|
||||
id: id,
|
||||
dst: dst,
|
||||
@ -209,4 +203,8 @@ func newConn(conn net.Conn, id *ID, dst *DstAddr, security Security) *Conn {
|
||||
writer: writer,
|
||||
security: security,
|
||||
}
|
||||
if err := c.sendRequest(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
@ -57,6 +57,7 @@ const (
|
||||
|
||||
// DstAddr store destination address
|
||||
type DstAddr struct {
|
||||
UDP bool
|
||||
AddrType byte
|
||||
Addr []byte
|
||||
Port uint
|
||||
@ -100,7 +101,7 @@ func (c *Client) New(conn net.Conn, dst *DstAddr) (net.Conn, error) {
|
||||
} else if c.tls {
|
||||
conn = tls.Client(conn, c.tlsConfig)
|
||||
}
|
||||
return newConn(conn, c.user[r], dst, c.security), nil
|
||||
return newConn(conn, c.user[r], dst, c.security)
|
||||
}
|
||||
|
||||
// NewClient return Client instance
|
||||
|
231
config/config.go
231
config/config.go
@ -11,6 +11,8 @@ import (
|
||||
|
||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
"github.com/Dreamacro/clash/component/auth"
|
||||
"github.com/Dreamacro/clash/component/fakeip"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/dns"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
@ -25,6 +27,7 @@ type General struct {
|
||||
Port int `json:"port"`
|
||||
SocksPort int `json:"socks-port"`
|
||||
RedirPort int `json:"redir-port"`
|
||||
Authentication []string `json:"authentication"`
|
||||
AllowLan bool `json:"allow-lan"`
|
||||
Mode T.Mode `json:"mode"`
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
@ -41,14 +44,22 @@ type DNS struct {
|
||||
Fallback []dns.NameServer `yaml:"fallback"`
|
||||
Listen string `yaml:"listen"`
|
||||
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||
FakeIPRange *fakeip.Pool
|
||||
}
|
||||
|
||||
// Experimental config
|
||||
type Experimental struct {
|
||||
IgnoreResolveFail bool `yaml:"ignore-resolve-fail"`
|
||||
}
|
||||
|
||||
// Config is clash config manager
|
||||
type Config struct {
|
||||
General *General
|
||||
DNS *DNS
|
||||
Rules []C.Rule
|
||||
Proxies map[string]C.Proxy
|
||||
General *General
|
||||
DNS *DNS
|
||||
Experimental *Experimental
|
||||
Rules []C.Rule
|
||||
Users []auth.AuthUser
|
||||
Proxies map[string]C.Proxy
|
||||
}
|
||||
|
||||
type rawDNS struct {
|
||||
@ -58,12 +69,14 @@ type rawDNS struct {
|
||||
Fallback []string `yaml:"fallback"`
|
||||
Listen string `yaml:"listen"`
|
||||
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||
FakeIPRange string `yaml:"fake-ip-range"`
|
||||
}
|
||||
|
||||
type rawConfig struct {
|
||||
Port int `yaml:"port"`
|
||||
SocksPort int `yaml:"socks-port"`
|
||||
RedirPort int `yaml:"redir-port"`
|
||||
Authentication []string `yaml:"authentication"`
|
||||
AllowLan bool `yaml:"allow-lan"`
|
||||
Mode T.Mode `yaml:"mode"`
|
||||
LogLevel log.LogLevel `yaml:"log-level"`
|
||||
@ -71,35 +84,56 @@ type rawConfig struct {
|
||||
ExternalUI string `yaml:"external-ui"`
|
||||
Secret string `yaml:"secret"`
|
||||
|
||||
DNS rawDNS `yaml:"dns"`
|
||||
Proxy []map[string]interface{} `yaml:"Proxy"`
|
||||
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
||||
Rule []string `yaml:"Rule"`
|
||||
DNS rawDNS `yaml:"dns"`
|
||||
Experimental Experimental `yaml:"experimental"`
|
||||
Proxy []map[string]interface{} `yaml:"Proxy"`
|
||||
ProxyGroup []map[string]interface{} `yaml:"Proxy Group"`
|
||||
Rule []string `yaml:"Rule"`
|
||||
}
|
||||
|
||||
// forward compatibility before 1.0
|
||||
func readRawConfig(path string) ([]byte, error) {
|
||||
data, err := ioutil.ReadFile(path)
|
||||
if err == nil && len(data) != 0 {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if filepath.Ext(path) != ".yaml" {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
path = path[:len(path)-5] + ".yml"
|
||||
return ioutil.ReadFile(path)
|
||||
}
|
||||
|
||||
func readConfig(path string) (*rawConfig, error) {
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
data, err := ioutil.ReadFile(path)
|
||||
data, err := readRawConfig(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("Configuration file %s is empty", C.Path.Config())
|
||||
return nil, fmt.Errorf("Configuration file %s is empty", path)
|
||||
}
|
||||
|
||||
// config with some default value
|
||||
rawConfig := &rawConfig{
|
||||
AllowLan: false,
|
||||
Mode: T.Rule,
|
||||
LogLevel: log.INFO,
|
||||
Rule: []string{},
|
||||
Proxy: []map[string]interface{}{},
|
||||
ProxyGroup: []map[string]interface{}{},
|
||||
AllowLan: false,
|
||||
Mode: T.Rule,
|
||||
Authentication: []string{},
|
||||
LogLevel: log.INFO,
|
||||
Rule: []string{},
|
||||
Proxy: []map[string]interface{}{},
|
||||
ProxyGroup: []map[string]interface{}{},
|
||||
Experimental: Experimental{
|
||||
IgnoreResolveFail: true,
|
||||
},
|
||||
DNS: rawDNS{
|
||||
Enable: false,
|
||||
Enable: false,
|
||||
FakeIPRange: "198.18.0.1/16",
|
||||
},
|
||||
}
|
||||
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
||||
@ -114,6 +148,7 @@ func Parse(path string) (*Config, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.Experimental = &rawCfg.Experimental
|
||||
|
||||
general, err := parseGeneral(rawCfg)
|
||||
if err != nil {
|
||||
@ -127,7 +162,7 @@ func Parse(path string) (*Config, error) {
|
||||
}
|
||||
config.Proxies = proxies
|
||||
|
||||
rules, err := parseRules(rawCfg)
|
||||
rules, err := parseRules(rawCfg, proxies)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -139,6 +174,8 @@ func Parse(path string) (*Config, error) {
|
||||
}
|
||||
config.DNS = dnsCfg
|
||||
|
||||
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@ -179,13 +216,15 @@ func parseGeneral(cfg *rawConfig) (*General, error) {
|
||||
|
||||
func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||
proxies := make(map[string]C.Proxy)
|
||||
proxyList := []string{}
|
||||
proxiesConfig := cfg.Proxy
|
||||
groupsConfig := cfg.ProxyGroup
|
||||
|
||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||
|
||||
proxies["DIRECT"] = adapters.NewDirect()
|
||||
proxies["REJECT"] = adapters.NewReject()
|
||||
proxies["DIRECT"] = adapters.NewProxy(adapters.NewDirect())
|
||||
proxies["REJECT"] = adapters.NewProxy(adapters.NewReject())
|
||||
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||
|
||||
// parse proxy
|
||||
for idx, mapping := range proxiesConfig {
|
||||
@ -194,8 +233,8 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||
return nil, fmt.Errorf("Proxy %d missing type", idx)
|
||||
}
|
||||
|
||||
var proxy C.Proxy
|
||||
var err error
|
||||
var proxy C.ProxyAdapter
|
||||
err := fmt.Errorf("cannot parse")
|
||||
switch proxyType {
|
||||
case "ss":
|
||||
ssOption := &adapters.ShadowSocksOption{}
|
||||
@ -236,7 +275,8 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||
if _, exist := proxies[proxy.Name()]; exist {
|
||||
return nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
||||
}
|
||||
proxies[proxy.Name()] = proxy
|
||||
proxies[proxy.Name()] = adapters.NewProxy(proxy)
|
||||
proxyList = append(proxyList, proxy.Name())
|
||||
}
|
||||
|
||||
// parse proxy group
|
||||
@ -250,9 +290,10 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||
if _, exist := proxies[groupName]; exist {
|
||||
return nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
||||
}
|
||||
var group C.Proxy
|
||||
var ps []C.Proxy
|
||||
var err error
|
||||
var group C.ProxyAdapter
|
||||
ps := []C.Proxy{}
|
||||
|
||||
err := fmt.Errorf("cannot parse")
|
||||
switch groupType {
|
||||
case "url-test":
|
||||
urlTestOption := &adapters.URLTestOption{}
|
||||
@ -290,23 +331,37 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||
}
|
||||
group, err = adapters.NewFallback(*fallbackOption, ps)
|
||||
case "load-balance":
|
||||
loadBalanceOption := &adapters.LoadBalanceOption{}
|
||||
err = decoder.Decode(mapping, loadBalanceOption)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
ps, err = getProxies(proxies, loadBalanceOption.Proxies)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
||||
}
|
||||
group, err = adapters.NewLoadBalance(*loadBalanceOption, ps)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Proxy %s: %s", groupName, err.Error())
|
||||
}
|
||||
proxies[groupName] = group
|
||||
proxies[groupName] = adapters.NewProxy(group)
|
||||
proxyList = append(proxyList, groupName)
|
||||
}
|
||||
|
||||
var ps []C.Proxy
|
||||
for _, v := range proxies {
|
||||
ps = append(ps, v)
|
||||
ps := []C.Proxy{}
|
||||
for _, v := range proxyList {
|
||||
ps = append(ps, proxies[v])
|
||||
}
|
||||
|
||||
proxies["GLOBAL"], _ = adapters.NewSelector("GLOBAL", ps)
|
||||
global, _ := adapters.NewSelector("GLOBAL", ps)
|
||||
proxies["GLOBAL"] = adapters.NewProxy(global)
|
||||
return proxies, nil
|
||||
}
|
||||
|
||||
func parseRules(cfg *rawConfig) ([]C.Rule, error) {
|
||||
func parseRules(cfg *rawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
||||
rules := []C.Rule{}
|
||||
|
||||
rulesConfig := cfg.Rule
|
||||
@ -325,28 +380,55 @@ func parseRules(cfg *rawConfig) ([]C.Rule, error) {
|
||||
payload = rule[1]
|
||||
target = rule[2]
|
||||
default:
|
||||
return nil, fmt.Errorf("Rules[%d] [- %s] error: format invalid", idx, line)
|
||||
return nil, fmt.Errorf("Rules[%d] [%s] error: format invalid", idx, line)
|
||||
}
|
||||
|
||||
if _, ok := proxies[target]; !ok {
|
||||
return nil, fmt.Errorf("Rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
||||
}
|
||||
|
||||
rule = trimArr(rule)
|
||||
var parsed C.Rule
|
||||
switch rule[0] {
|
||||
case "DOMAIN":
|
||||
rules = append(rules, R.NewDomain(payload, target))
|
||||
parsed = R.NewDomain(payload, target)
|
||||
case "DOMAIN-SUFFIX":
|
||||
rules = append(rules, R.NewDomainSuffix(payload, target))
|
||||
parsed = R.NewDomainSuffix(payload, target)
|
||||
case "DOMAIN-KEYWORD":
|
||||
rules = append(rules, R.NewDomainKeyword(payload, target))
|
||||
parsed = R.NewDomainKeyword(payload, target)
|
||||
case "GEOIP":
|
||||
rules = append(rules, R.NewGEOIP(payload, target))
|
||||
parsed = R.NewGEOIP(payload, target)
|
||||
case "IP-CIDR", "IP-CIDR6":
|
||||
rules = append(rules, R.NewIPCIDR(payload, target, false))
|
||||
if rule := R.NewIPCIDR(payload, target, false); rule != nil {
|
||||
parsed = rule
|
||||
}
|
||||
// deprecated when bump to 1.0
|
||||
case "SOURCE-IP-CIDR":
|
||||
rules = append(rules, R.NewIPCIDR(payload, target, true))
|
||||
fallthrough
|
||||
case "SRC-IP-CIDR":
|
||||
if rule := R.NewIPCIDR(payload, target, true); rule != nil {
|
||||
parsed = rule
|
||||
}
|
||||
case "SRC-PORT":
|
||||
if rule := R.NewPort(payload, target, true); rule != nil {
|
||||
parsed = rule
|
||||
}
|
||||
case "DST-PORT":
|
||||
if rule := R.NewPort(payload, target, false); rule != nil {
|
||||
parsed = rule
|
||||
}
|
||||
case "MATCH":
|
||||
fallthrough
|
||||
// deprecated when bump to 1.0
|
||||
case "FINAL":
|
||||
rules = append(rules, R.NewFinal(target))
|
||||
parsed = R.NewMatch(target)
|
||||
}
|
||||
|
||||
if parsed == nil {
|
||||
return nil, fmt.Errorf("Rules[%d] [%s] error: payload invalid", idx, line)
|
||||
}
|
||||
|
||||
rules = append(rules, parsed)
|
||||
}
|
||||
|
||||
return rules, nil
|
||||
@ -374,33 +456,45 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
||||
|
||||
for idx, server := range servers {
|
||||
// parse without scheme .e.g 8.8.8.8:53
|
||||
if host, err := hostWithDefaultPort(server, "53"); err == nil {
|
||||
nameservers = append(
|
||||
nameservers,
|
||||
dns.NameServer{Addr: host},
|
||||
)
|
||||
continue
|
||||
if !strings.Contains(server, "://") {
|
||||
server = "udp://" + server
|
||||
}
|
||||
|
||||
u, err := url.Parse(server)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||
}
|
||||
|
||||
if u.Scheme != "tls" {
|
||||
var host, dnsNetType string
|
||||
switch u.Scheme {
|
||||
case "udp":
|
||||
host, err = hostWithDefaultPort(u.Host, "53")
|
||||
dnsNetType = "" // UDP
|
||||
case "tcp":
|
||||
host, err = hostWithDefaultPort(u.Host, "53")
|
||||
dnsNetType = "tcp" // TCP
|
||||
case "tls":
|
||||
host, err = hostWithDefaultPort(u.Host, "853")
|
||||
dnsNetType = "tcp-tls" // DNS over TLS
|
||||
case "https":
|
||||
clearURL := url.URL{Scheme: "https", Host: u.Host, Path: u.Path}
|
||||
host = clearURL.String()
|
||||
dnsNetType = "https" // DNS over HTTPS
|
||||
default:
|
||||
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||
}
|
||||
|
||||
host, err := hostWithDefaultPort(u.Host, "853")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||
}
|
||||
|
||||
nameservers = append(
|
||||
nameservers,
|
||||
dns.NameServer{
|
||||
Net: "tcp-tls",
|
||||
Net: dnsNetType,
|
||||
Addr: host,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return nameservers, nil
|
||||
}
|
||||
|
||||
@ -412,16 +506,41 @@ func parseDNS(cfg rawDNS) (*DNS, error) {
|
||||
dnsCfg := &DNS{
|
||||
Enable: cfg.Enable,
|
||||
Listen: cfg.Listen,
|
||||
IPv6: cfg.IPv6,
|
||||
EnhancedMode: cfg.EnhancedMode,
|
||||
}
|
||||
|
||||
if nameserver, err := parseNameServer(cfg.NameServer); err == nil {
|
||||
dnsCfg.NameServer = nameserver
|
||||
var err error
|
||||
if dnsCfg.NameServer, err = parseNameServer(cfg.NameServer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if fallback, err := parseNameServer(cfg.Fallback); err == nil {
|
||||
dnsCfg.Fallback = fallback
|
||||
if dnsCfg.Fallback, err = parseNameServer(cfg.Fallback); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cfg.EnhancedMode == dns.FAKEIP {
|
||||
_, ipnet, err := net.ParseCIDR(cfg.FakeIPRange)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pool, err := fakeip.New(ipnet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dnsCfg.FakeIPRange = pool
|
||||
}
|
||||
|
||||
return dnsCfg, nil
|
||||
}
|
||||
|
||||
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
||||
users := make([]auth.AuthUser, 0)
|
||||
for _, line := range rawRecords {
|
||||
userData := strings.SplitN(line, ":", 2)
|
||||
if len(userData) == 2 {
|
||||
users = append(users, auth.AuthUser{User: userData[0], Pass: userData[1]})
|
||||
}
|
||||
}
|
||||
return users
|
||||
}
|
||||
|
@ -63,9 +63,9 @@ func Init(dir string) error {
|
||||
}
|
||||
}
|
||||
|
||||
// initial config.yml
|
||||
// initial config.yaml
|
||||
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
||||
log.Info("Can't find config, create a empty file")
|
||||
log.Info("Can't find config, create an empty file")
|
||||
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
||||
}
|
||||
|
||||
|
@ -2,6 +2,7 @@ package constant
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Adapter Type
|
||||
@ -15,18 +16,35 @@ const (
|
||||
Http
|
||||
URLTest
|
||||
Vmess
|
||||
LoadBalance
|
||||
)
|
||||
|
||||
type ServerAdapter interface {
|
||||
net.Conn
|
||||
Metadata() *Metadata
|
||||
Close()
|
||||
}
|
||||
|
||||
type ProxyAdapter interface {
|
||||
Name() string
|
||||
Type() AdapterType
|
||||
Dial(metadata *Metadata) (net.Conn, error)
|
||||
DialUDP(metadata *Metadata) (net.PacketConn, net.Addr, error)
|
||||
SupportUDP() bool
|
||||
Destroy()
|
||||
MarshalJSON() ([]byte, error)
|
||||
}
|
||||
|
||||
type DelayHistory struct {
|
||||
Time time.Time `json:"time"`
|
||||
Delay uint16 `json:"delay"`
|
||||
}
|
||||
|
||||
type Proxy interface {
|
||||
Name() string
|
||||
Type() AdapterType
|
||||
Generator(metadata *Metadata) (net.Conn, error)
|
||||
MarshalJSON() ([]byte, error)
|
||||
ProxyAdapter
|
||||
Alive() bool
|
||||
DelayHistory() []DelayHistory
|
||||
LastDelay() uint16
|
||||
URLTest(url string) (uint16, error)
|
||||
}
|
||||
|
||||
// AdapterType is enum of adapter type
|
||||
@ -52,6 +70,8 @@ func (at AdapterType) String() string {
|
||||
return "URLTest"
|
||||
case Vmess:
|
||||
return "Vmess"
|
||||
case LoadBalance:
|
||||
return "LoadBalance"
|
||||
default:
|
||||
return "Unknow"
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ const (
|
||||
TCP NetWork = iota
|
||||
UDP
|
||||
|
||||
HTTP SourceType = iota
|
||||
HTTP Type = iota
|
||||
SOCKS
|
||||
REDIR
|
||||
)
|
||||
@ -27,26 +27,27 @@ func (n *NetWork) String() string {
|
||||
return "udp"
|
||||
}
|
||||
|
||||
type SourceType int
|
||||
type Type int
|
||||
|
||||
// Metadata is used to store connection address
|
||||
type Metadata struct {
|
||||
NetWork NetWork
|
||||
Source SourceType
|
||||
SourceIP *net.IP
|
||||
Type Type
|
||||
SrcIP *net.IP
|
||||
DstIP *net.IP
|
||||
SrcPort string
|
||||
DstPort string
|
||||
AddrType int
|
||||
Host string
|
||||
IP *net.IP
|
||||
Port string
|
||||
}
|
||||
|
||||
func (m *Metadata) String() string {
|
||||
if m.Host == "" {
|
||||
return m.IP.String()
|
||||
return m.DstIP.String()
|
||||
}
|
||||
return m.Host
|
||||
}
|
||||
|
||||
func (m *Metadata) Valid() bool {
|
||||
return m.Host != "" || m.IP != nil
|
||||
return m.Host != "" || m.DstIP != nil
|
||||
}
|
||||
|
@ -27,6 +27,7 @@ func init() {
|
||||
} else {
|
||||
homedir = currentUser.HomeDir
|
||||
}
|
||||
|
||||
homedir = P.Join(homedir, ".config", Name)
|
||||
Path = &path{homedir: homedir}
|
||||
}
|
||||
@ -41,7 +42,7 @@ func (p *path) HomeDir() string {
|
||||
}
|
||||
|
||||
func (p *path) Config() string {
|
||||
return P.Join(p.homedir, "config.yml")
|
||||
return P.Join(p.homedir, "config.yaml")
|
||||
}
|
||||
|
||||
func (p *path) MMDB() string {
|
||||
|
@ -7,8 +7,10 @@ const (
|
||||
DomainKeyword
|
||||
GEOIP
|
||||
IPCIDR
|
||||
SourceIPCIDR
|
||||
FINAL
|
||||
SrcIPCIDR
|
||||
SrcPort
|
||||
DstPort
|
||||
MATCH
|
||||
)
|
||||
|
||||
type RuleType int
|
||||
@ -25,10 +27,14 @@ func (rt RuleType) String() string {
|
||||
return "GEOIP"
|
||||
case IPCIDR:
|
||||
return "IPCIDR"
|
||||
case SourceIPCIDR:
|
||||
return "SourceIPCIDR"
|
||||
case FINAL:
|
||||
return "FINAL"
|
||||
case SrcIPCIDR:
|
||||
return "SrcIPCIDR"
|
||||
case SrcPort:
|
||||
return "SrcPort"
|
||||
case DstPort:
|
||||
return "DstPort"
|
||||
case MATCH:
|
||||
return "MATCH"
|
||||
default:
|
||||
return "Unknow"
|
||||
}
|
||||
|
6
constant/version.go
Normal file
6
constant/version.go
Normal file
@ -0,0 +1,6 @@
|
||||
package constant
|
||||
|
||||
var (
|
||||
Version = "unknown version"
|
||||
BuildTime = "unknown time"
|
||||
)
|
266
dns/client.go
266
dns/client.go
@ -2,272 +2,20 @@ package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"github.com/Dreamacro/clash/common/picker"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
geoip2 "github.com/oschwald/geoip2-golang"
|
||||
)
|
||||
|
||||
var (
|
||||
globalSessionCache = tls.NewLRUClientSessionCache(64)
|
||||
|
||||
mmdb *geoip2.Reader
|
||||
once sync.Once
|
||||
resolver *Resolver
|
||||
)
|
||||
|
||||
type Resolver struct {
|
||||
ipv6 bool
|
||||
mapping bool
|
||||
fallback []*nameserver
|
||||
main []*nameserver
|
||||
cache *cache.Cache
|
||||
}
|
||||
|
||||
type result struct {
|
||||
Msg *D.Msg
|
||||
Error error
|
||||
}
|
||||
|
||||
func isIPRequest(q D.Question) bool {
|
||||
if q.Qclass == D.ClassINET && (q.Qtype == D.TypeA || q.Qtype == D.TypeAAAA) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *Resolver) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||
if len(m.Question) == 0 {
|
||||
return nil, errors.New("should have one question at least")
|
||||
}
|
||||
|
||||
q := m.Question[0]
|
||||
cache, expireTime := r.cache.GetWithExpire(q.String())
|
||||
if cache != nil {
|
||||
msg = cache.(*D.Msg).Copy()
|
||||
if len(msg.Answer) > 0 {
|
||||
ttl := uint32(expireTime.Sub(time.Now()).Seconds())
|
||||
for _, answer := range msg.Answer {
|
||||
answer.Header().Ttl = ttl
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if msg != nil {
|
||||
putMsgToCache(r.cache, q.String(), msg)
|
||||
if r.mapping {
|
||||
ips, err := r.msgToIP(msg)
|
||||
if err != nil {
|
||||
log.Debugln("[DNS] msg to ip error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
for _, ip := range ips {
|
||||
putMsgToCache(r.cache, ip.String(), msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
isIPReq := isIPRequest(q)
|
||||
if isIPReq {
|
||||
msg, err = r.resolveIP(m)
|
||||
return
|
||||
}
|
||||
|
||||
msg, err = r.exchange(r.main, m)
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) exchange(servers []*nameserver, m *D.Msg) (msg *D.Msg, err error) {
|
||||
in := make(chan interface{})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
fast := picker.SelectFast(ctx, in)
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(servers))
|
||||
for _, server := range servers {
|
||||
go func(s *nameserver) {
|
||||
defer wg.Done()
|
||||
msg, _, err := s.Client.Exchange(m, s.Address)
|
||||
if err != nil || msg.Rcode != D.RcodeSuccess {
|
||||
return
|
||||
}
|
||||
in <- &result{Msg: msg, Error: err}
|
||||
}(server)
|
||||
}
|
||||
|
||||
// release in channel
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(in)
|
||||
}()
|
||||
|
||||
elm, exist := <-fast
|
||||
if !exist {
|
||||
return nil, errors.New("All DNS requests failed")
|
||||
}
|
||||
|
||||
resp := elm.(*result)
|
||||
msg, err = resp.Msg, resp.Error
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) resolveIP(m *D.Msg) (msg *D.Msg, err error) {
|
||||
msgCh := r.resolve(r.main, m)
|
||||
if r.fallback == nil {
|
||||
res := <-msgCh
|
||||
msg, err = res.Msg, res.Error
|
||||
return
|
||||
}
|
||||
fallbackMsg := r.resolve(r.fallback, m)
|
||||
res := <-msgCh
|
||||
if res.Error == nil {
|
||||
if mmdb == nil {
|
||||
return nil, errors.New("GeoIP can't use")
|
||||
}
|
||||
|
||||
ips, err := r.msgToIP(res.Msg)
|
||||
if err == nil {
|
||||
if record, _ := mmdb.Country(ips[0]); record.Country.IsoCode == "CN" || record.Country.IsoCode == "" {
|
||||
// release channel
|
||||
go func() { <-fallbackMsg }()
|
||||
msg = res.Msg
|
||||
return msg, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res = <-fallbackMsg
|
||||
msg, err = res.Msg, res.Error
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) ResolveIP(host string) (ip net.IP, err error) {
|
||||
ip = net.ParseIP(host)
|
||||
if ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
query := &D.Msg{}
|
||||
dnsType := D.TypeA
|
||||
if r.ipv6 {
|
||||
dnsType = D.TypeAAAA
|
||||
}
|
||||
query.SetQuestion(D.Fqdn(host), dnsType)
|
||||
|
||||
msg, err := r.Exchange(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ips []net.IP
|
||||
ips, err = r.msgToIP(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ip = ips[0]
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) msgToIP(msg *D.Msg) ([]net.IP, error) {
|
||||
var ips []net.IP
|
||||
|
||||
for _, answer := range msg.Answer {
|
||||
switch ans := answer.(type) {
|
||||
case *D.AAAA:
|
||||
ips = append(ips, ans.AAAA)
|
||||
case *D.A:
|
||||
ips = append(ips, ans.A)
|
||||
}
|
||||
}
|
||||
|
||||
if len(ips) == 0 {
|
||||
return nil, errors.New("Can't parse msg")
|
||||
}
|
||||
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) IPToHost(ip net.IP) (string, bool) {
|
||||
cache := r.cache.Get(ip.String())
|
||||
if cache == nil {
|
||||
return "", false
|
||||
}
|
||||
fqdn := cache.(*D.Msg).Question[0].Name
|
||||
return strings.TrimRight(fqdn, "."), true
|
||||
}
|
||||
|
||||
func (r *Resolver) resolve(client []*nameserver, msg *D.Msg) <-chan *result {
|
||||
ch := make(chan *result)
|
||||
go func() {
|
||||
res, err := r.exchange(client, msg)
|
||||
ch <- &result{Msg: res, Error: err}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (r *Resolver) IsMapping() bool {
|
||||
return r.mapping
|
||||
}
|
||||
|
||||
type NameServer struct {
|
||||
Net string
|
||||
Addr string
|
||||
}
|
||||
|
||||
type nameserver struct {
|
||||
Client *D.Client
|
||||
type client struct {
|
||||
*D.Client
|
||||
Address string
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Main, Fallback []NameServer
|
||||
IPv6 bool
|
||||
EnhancedMode EnhancedMode
|
||||
func (c *client) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||
return c.ExchangeContext(context.Background(), m)
|
||||
}
|
||||
|
||||
func transform(servers []NameServer) []*nameserver {
|
||||
var ret []*nameserver
|
||||
for _, s := range servers {
|
||||
ret = append(ret, &nameserver{
|
||||
Client: &D.Client{
|
||||
Net: s.Net,
|
||||
TLSConfig: &tls.Config{
|
||||
ClientSessionCache: globalSessionCache,
|
||||
},
|
||||
},
|
||||
Address: s.Addr,
|
||||
})
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func New(config Config) *Resolver {
|
||||
once.Do(func() {
|
||||
mmdb, _ = geoip2.Open(C.Path.MMDB())
|
||||
})
|
||||
|
||||
r := &Resolver{
|
||||
main: transform(config.Main),
|
||||
ipv6: config.IPv6,
|
||||
cache: cache.New(time.Second * 60),
|
||||
mapping: config.EnhancedMode == MAPPING,
|
||||
}
|
||||
if config.Fallback != nil {
|
||||
r.fallback = transform(config.Fallback)
|
||||
}
|
||||
return r
|
||||
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||
msg, _, err = c.Client.ExchangeContext(ctx, m, c.Address)
|
||||
return
|
||||
}
|
||||
|
75
dns/doh.go
Normal file
75
dns/doh.go
Normal file
@ -0,0 +1,75 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
const (
|
||||
// dotMimeType is the DoH mimetype that should be used.
|
||||
dotMimeType = "application/dns-message"
|
||||
|
||||
// dotPath is the URL path that should be used.
|
||||
dotPath = "/dns-query"
|
||||
)
|
||||
|
||||
var dohTransport = &http.Transport{
|
||||
TLSClientConfig: &tls.Config{ClientSessionCache: globalSessionCache},
|
||||
}
|
||||
|
||||
type dohClient struct {
|
||||
url string
|
||||
}
|
||||
|
||||
func (dc *dohClient) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||
return dc.ExchangeContext(context.Background(), m)
|
||||
}
|
||||
|
||||
func (dc *dohClient) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||
req, err := dc.newRequest(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req = req.WithContext(ctx)
|
||||
return dc.doRequest(req)
|
||||
}
|
||||
|
||||
// newRequest returns a new DoH request given a dns.Msg.
|
||||
func (dc *dohClient) newRequest(m *D.Msg) (*http.Request, error) {
|
||||
buf, err := m.Pack()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, dc.url+"?bla=foo:443", bytes.NewReader(buf))
|
||||
if err != nil {
|
||||
return req, err
|
||||
}
|
||||
|
||||
req.Header.Set("content-type", dotMimeType)
|
||||
req.Header.Set("accept", dotMimeType)
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func (dc *dohClient) doRequest(req *http.Request) (msg *D.Msg, err error) {
|
||||
client := &http.Client{Transport: dohTransport}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
buf, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msg = &D.Msg{}
|
||||
err = msg.Unpack(buf)
|
||||
return msg, err
|
||||
}
|
32
dns/iputil.go
Normal file
32
dns/iputil.go
Normal file
@ -0,0 +1,32 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
var (
|
||||
errIPNotFound = errors.New("cannot found ip")
|
||||
)
|
||||
|
||||
// ResolveIP with a host, return ip
|
||||
func ResolveIP(host string) (net.IP, error) {
|
||||
if DefaultResolver != nil {
|
||||
if DefaultResolver.ipv6 {
|
||||
return DefaultResolver.ResolveIP(host)
|
||||
}
|
||||
return DefaultResolver.ResolveIPv4(host)
|
||||
}
|
||||
|
||||
ip := net.ParseIP(host)
|
||||
if ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ipAddr.IP, nil
|
||||
}
|
299
dns/resolver.go
Normal file
299
dns/resolver.go
Normal file
@ -0,0 +1,299 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"github.com/Dreamacro/clash/common/picker"
|
||||
"github.com/Dreamacro/clash/component/fakeip"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
geoip2 "github.com/oschwald/geoip2-golang"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultResolver aim to resolve ip with host
|
||||
DefaultResolver *Resolver
|
||||
)
|
||||
|
||||
var (
|
||||
globalSessionCache = tls.NewLRUClientSessionCache(64)
|
||||
|
||||
mmdb *geoip2.Reader
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
type resolver interface {
|
||||
Exchange(m *D.Msg) (msg *D.Msg, err error)
|
||||
ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
Msg *D.Msg
|
||||
Error error
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
ipv6 bool
|
||||
mapping bool
|
||||
fakeip bool
|
||||
pool *fakeip.Pool
|
||||
fallback []resolver
|
||||
main []resolver
|
||||
cache *cache.Cache
|
||||
}
|
||||
|
||||
// ResolveIP request with TypeA and TypeAAAA, priority return TypeAAAA
|
||||
func (r *Resolver) ResolveIP(host string) (ip net.IP, err error) {
|
||||
ip = net.ParseIP(host)
|
||||
if ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
ch := make(chan net.IP)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
ip, err := r.resolveIP(host, D.TypeA)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ch <- ip
|
||||
}()
|
||||
|
||||
ip, err = r.resolveIP(host, D.TypeAAAA)
|
||||
if err == nil {
|
||||
go func() {
|
||||
<-ch
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
ip, open := <-ch
|
||||
if !open {
|
||||
return nil, errIPNotFound
|
||||
}
|
||||
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
// ResolveIPv4 request with TypeA
|
||||
func (r *Resolver) ResolveIPv4(host string) (ip net.IP, err error) {
|
||||
ip = net.ParseIP(host)
|
||||
if ip != nil {
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
query := &D.Msg{}
|
||||
query.SetQuestion(D.Fqdn(host), D.TypeA)
|
||||
|
||||
msg, err := r.Exchange(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ips := r.msgToIP(msg)
|
||||
if len(ips) == 0 {
|
||||
return nil, errIPNotFound
|
||||
}
|
||||
|
||||
ip = ips[0]
|
||||
return
|
||||
}
|
||||
|
||||
// Exchange a batch of dns request, and it use cache
|
||||
func (r *Resolver) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||
if len(m.Question) == 0 {
|
||||
return nil, errors.New("should have one question at least")
|
||||
}
|
||||
|
||||
q := m.Question[0]
|
||||
cache, expireTime := r.cache.GetWithExpire(q.String())
|
||||
if cache != nil {
|
||||
msg = cache.(*D.Msg).Copy()
|
||||
setMsgTTL(msg, uint32(expireTime.Sub(time.Now()).Seconds()))
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if msg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
putMsgToCache(r.cache, q.String(), msg)
|
||||
if r.mapping {
|
||||
ips := r.msgToIP(msg)
|
||||
for _, ip := range ips {
|
||||
putMsgToCache(r.cache, ip.String(), msg)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
isIPReq := isIPRequest(q)
|
||||
if isIPReq {
|
||||
msg, err = r.fallbackExchange(m)
|
||||
return
|
||||
}
|
||||
|
||||
msg, err = r.batchExchange(r.main, m)
|
||||
return
|
||||
}
|
||||
|
||||
// IPToHost return fake-ip or redir-host mapping host
|
||||
func (r *Resolver) IPToHost(ip net.IP) (string, bool) {
|
||||
cache := r.cache.Get(ip.String())
|
||||
if cache == nil {
|
||||
return "", false
|
||||
}
|
||||
fqdn := cache.(*D.Msg).Question[0].Name
|
||||
return strings.TrimRight(fqdn, "."), true
|
||||
}
|
||||
|
||||
func (r *Resolver) IsMapping() bool {
|
||||
return r.mapping
|
||||
}
|
||||
|
||||
func (r *Resolver) IsFakeIP() bool {
|
||||
return r.fakeip
|
||||
}
|
||||
|
||||
func (r *Resolver) batchExchange(clients []resolver, m *D.Msg) (msg *D.Msg, err error) {
|
||||
in := make(chan interface{})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
fast := picker.SelectFast(ctx, in)
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(clients))
|
||||
for _, r := range clients {
|
||||
go func(r resolver) {
|
||||
defer wg.Done()
|
||||
msg, err := r.ExchangeContext(ctx, m)
|
||||
if err != nil || msg.Rcode != D.RcodeSuccess {
|
||||
return
|
||||
}
|
||||
in <- msg
|
||||
}(r)
|
||||
}
|
||||
|
||||
// release in channel
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(in)
|
||||
}()
|
||||
|
||||
elm, exist := <-fast
|
||||
if !exist {
|
||||
return nil, errors.New("All DNS requests failed")
|
||||
}
|
||||
|
||||
msg = elm.(*D.Msg)
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) fallbackExchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||
msgCh := r.asyncExchange(r.main, m)
|
||||
if r.fallback == nil {
|
||||
res := <-msgCh
|
||||
msg, err = res.Msg, res.Error
|
||||
return
|
||||
}
|
||||
fallbackMsg := r.asyncExchange(r.fallback, m)
|
||||
res := <-msgCh
|
||||
if res.Error == nil {
|
||||
if mmdb == nil {
|
||||
return nil, errors.New("GeoIP cannot use")
|
||||
}
|
||||
|
||||
if ips := r.msgToIP(res.Msg); len(ips) != 0 {
|
||||
if record, _ := mmdb.Country(ips[0]); record.Country.IsoCode == "CN" || record.Country.IsoCode == "" {
|
||||
// release channel
|
||||
go func() { <-fallbackMsg }()
|
||||
msg = res.Msg
|
||||
return msg, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res = <-fallbackMsg
|
||||
msg, err = res.Msg, res.Error
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) resolveIP(host string, dnsType uint16) (ip net.IP, err error) {
|
||||
query := &D.Msg{}
|
||||
query.SetQuestion(D.Fqdn(host), dnsType)
|
||||
|
||||
msg, err := r.Exchange(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ips := r.msgToIP(msg)
|
||||
if len(ips) == 0 {
|
||||
return nil, errIPNotFound
|
||||
}
|
||||
|
||||
ip = ips[0]
|
||||
return
|
||||
}
|
||||
|
||||
func (r *Resolver) msgToIP(msg *D.Msg) []net.IP {
|
||||
ips := []net.IP{}
|
||||
|
||||
for _, answer := range msg.Answer {
|
||||
switch ans := answer.(type) {
|
||||
case *D.AAAA:
|
||||
ips = append(ips, ans.AAAA)
|
||||
case *D.A:
|
||||
ips = append(ips, ans.A)
|
||||
}
|
||||
}
|
||||
|
||||
return ips
|
||||
}
|
||||
|
||||
func (r *Resolver) asyncExchange(client []resolver, msg *D.Msg) <-chan *result {
|
||||
ch := make(chan *result)
|
||||
go func() {
|
||||
res, err := r.batchExchange(client, msg)
|
||||
ch <- &result{Msg: res, Error: err}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
type NameServer struct {
|
||||
Net string
|
||||
Addr string
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Main, Fallback []NameServer
|
||||
IPv6 bool
|
||||
EnhancedMode EnhancedMode
|
||||
Pool *fakeip.Pool
|
||||
}
|
||||
|
||||
func New(config Config) *Resolver {
|
||||
once.Do(func() {
|
||||
mmdb, _ = geoip2.Open(C.Path.MMDB())
|
||||
})
|
||||
|
||||
r := &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: transform(config.Main),
|
||||
cache: cache.New(time.Second * 60),
|
||||
mapping: config.EnhancedMode == MAPPING,
|
||||
fakeip: config.EnhancedMode == FAKEIP,
|
||||
pool: config.Pool,
|
||||
}
|
||||
if len(config.Fallback) != 0 {
|
||||
r.fallback = transform(config.Fallback)
|
||||
}
|
||||
return r
|
||||
}
|
@ -1,14 +1,20 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/log"
|
||||
"github.com/miekg/dns"
|
||||
D "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
var (
|
||||
address string
|
||||
server = &Server{}
|
||||
|
||||
dnsDefaultTTL uint32 = 600
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
@ -17,9 +23,25 @@ type Server struct {
|
||||
}
|
||||
|
||||
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
|
||||
if s.r.IsFakeIP() {
|
||||
msg, err := s.handleFakeIP(r)
|
||||
if err != nil {
|
||||
D.HandleFailed(w, r)
|
||||
return
|
||||
}
|
||||
msg.SetReply(r)
|
||||
w.WriteMsg(msg)
|
||||
return
|
||||
}
|
||||
|
||||
msg, err := s.r.Exchange(r)
|
||||
|
||||
if err != nil {
|
||||
if len(r.Question) > 0 {
|
||||
q := r.Question[0]
|
||||
qString := fmt.Sprintf("%s %s %s", q.Name, D.Class(q.Qclass).String(), D.Type(q.Qtype).String())
|
||||
log.Debugln("[DNS Server] Exchange %s failed: %v", qString, err)
|
||||
}
|
||||
D.HandleFailed(w, r)
|
||||
return
|
||||
}
|
||||
@ -27,15 +49,57 @@ func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
|
||||
w.WriteMsg(msg)
|
||||
}
|
||||
|
||||
func ReCreateServer(addr string, resolver *Resolver) error {
|
||||
if server.Server != nil {
|
||||
server.Shutdown()
|
||||
func (s *Server) handleFakeIP(r *D.Msg) (msg *D.Msg, err error) {
|
||||
if len(r.Question) == 0 {
|
||||
err = errors.New("should have one question at least")
|
||||
return
|
||||
}
|
||||
|
||||
q := r.Question[0]
|
||||
|
||||
cache := s.r.cache.Get("fakeip:" + q.String())
|
||||
if cache != nil {
|
||||
msg = cache.(*D.Msg).Copy()
|
||||
setMsgTTL(msg, 1)
|
||||
return
|
||||
}
|
||||
|
||||
var ip net.IP
|
||||
defer func() {
|
||||
if msg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
putMsgToCache(s.r.cache, "fakeip:"+q.String(), msg)
|
||||
putMsgToCache(s.r.cache, ip.String(), msg)
|
||||
|
||||
setMsgTTL(msg, 1)
|
||||
}()
|
||||
|
||||
rr := &D.A{}
|
||||
rr.Hdr = dns.RR_Header{Name: r.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: dnsDefaultTTL}
|
||||
ip = s.r.pool.Get()
|
||||
rr.A = ip
|
||||
msg = r.Copy()
|
||||
msg.Answer = []D.RR{rr}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) setReslover(r *Resolver) {
|
||||
s.r = r
|
||||
}
|
||||
|
||||
func ReCreateServer(addr string, resolver *Resolver) error {
|
||||
if addr == address {
|
||||
server.setReslover(resolver)
|
||||
return nil
|
||||
}
|
||||
|
||||
if server.Server != nil {
|
||||
server.Shutdown()
|
||||
address = ""
|
||||
}
|
||||
|
||||
_, port, err := net.SplitHostPort(addr)
|
||||
if port == "0" || port == "" || err != nil {
|
||||
return nil
|
||||
|
62
dns/util.go
62
dns/util.go
@ -1,6 +1,7 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
@ -70,7 +71,7 @@ func (e EnhancedMode) String() string {
|
||||
case NORMAL:
|
||||
return "normal"
|
||||
case FAKEIP:
|
||||
return "fakeip"
|
||||
return "fake-ip"
|
||||
case MAPPING:
|
||||
return "redir-host"
|
||||
default:
|
||||
@ -79,11 +80,62 @@ func (e EnhancedMode) String() string {
|
||||
}
|
||||
|
||||
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
|
||||
if len(msg.Answer) == 0 {
|
||||
log.Debugln("[DNS] answer length is zero: %#v", msg)
|
||||
var ttl time.Duration
|
||||
if len(msg.Answer) != 0 {
|
||||
ttl = time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
||||
} else if len(msg.Ns) != 0 {
|
||||
ttl = time.Duration(msg.Ns[0].Header().Ttl) * time.Second
|
||||
} else if len(msg.Extra) != 0 {
|
||||
ttl = time.Duration(msg.Extra[0].Header().Ttl) * time.Second
|
||||
} else {
|
||||
log.Debugln("[DNS] response msg error: %#v", msg)
|
||||
return
|
||||
}
|
||||
|
||||
ttl := time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
||||
c.Put(key, msg, ttl)
|
||||
c.Put(key, msg.Copy(), ttl)
|
||||
}
|
||||
|
||||
func setMsgTTL(msg *D.Msg, ttl uint32) {
|
||||
for _, answer := range msg.Answer {
|
||||
answer.Header().Ttl = ttl
|
||||
}
|
||||
|
||||
for _, ns := range msg.Ns {
|
||||
ns.Header().Ttl = ttl
|
||||
}
|
||||
|
||||
for _, extra := range msg.Extra {
|
||||
extra.Header().Ttl = ttl
|
||||
}
|
||||
}
|
||||
|
||||
func isIPRequest(q D.Question) bool {
|
||||
if q.Qclass == D.ClassINET && (q.Qtype == D.TypeA || q.Qtype == D.TypeAAAA) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func transform(servers []NameServer) []resolver {
|
||||
ret := []resolver{}
|
||||
for _, s := range servers {
|
||||
if s.Net == "https" {
|
||||
ret = append(ret, &dohClient{url: s.Addr})
|
||||
continue
|
||||
}
|
||||
|
||||
ret = append(ret, &client{
|
||||
Client: &D.Client{
|
||||
Net: s.Net,
|
||||
TLSConfig: &tls.Config{
|
||||
ClientSessionCache: globalSessionCache,
|
||||
// alpn identifier, see https://tools.ietf.org/html/draft-hoffman-dprive-dns-tls-alpn-00#page-6
|
||||
NextProtos: []string{"dns"},
|
||||
},
|
||||
UDPSize: 4096,
|
||||
},
|
||||
Address: s.Addr,
|
||||
})
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
18
go.mod
18
go.mod
@ -1,20 +1,20 @@
|
||||
module github.com/Dreamacro/clash
|
||||
|
||||
require (
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.3-0.20190202135136-da4602d8f112
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.3
|
||||
github.com/eapache/queue v1.1.0 // indirect
|
||||
github.com/go-chi/chi v4.0.1+incompatible
|
||||
github.com/go-chi/chi v4.0.2+incompatible
|
||||
github.com/go-chi/cors v1.0.0
|
||||
github.com/go-chi/render v1.0.1
|
||||
github.com/gofrs/uuid v3.2.0+incompatible
|
||||
github.com/gorilla/websocket v1.4.0
|
||||
github.com/miekg/dns v1.1.4
|
||||
github.com/oschwald/geoip2-golang v1.2.1
|
||||
github.com/oschwald/maxminddb-golang v1.3.0 // indirect
|
||||
github.com/sirupsen/logrus v1.3.0
|
||||
golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613
|
||||
golang.org/x/net v0.0.0-20181108082009-03003ca0c849 // indirect
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect
|
||||
github.com/miekg/dns v1.1.14
|
||||
github.com/oschwald/geoip2-golang v1.3.0
|
||||
github.com/oschwald/maxminddb-golang v1.3.1 // indirect
|
||||
github.com/sirupsen/logrus v1.4.2
|
||||
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect
|
||||
gopkg.in/eapache/channels.v1 v1.1.0
|
||||
gopkg.in/yaml.v2 v2.2.2
|
||||
)
|
||||
|
47
go.sum
47
go.sum
@ -1,13 +1,13 @@
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.3-0.20190202135136-da4602d8f112 h1:1axYxE0ZLJy40+ulq46XQt7MaJDJr4iGer1NQz7jmKw=
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.3-0.20190202135136-da4602d8f112/go.mod h1:giIuN+TuUudTxHc1jjTOyyQYiJ3VXp1pWOHdJbSCAPo=
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.3 h1:1ffY/q4e3o+MnztYgIq1iZiX1BWoWQ6D3AIO1kkb8bc=
|
||||
github.com/Dreamacro/go-shadowsocks2 v0.1.3/go.mod h1:0x17IhQ+mlY6q/ffKRpzaE7u4aHMxxnitTRSrV5G6TU=
|
||||
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 v4.0.1+incompatible h1:RSRC5qmFPtO90t7pTL0DBMNpZFsb/sHF3RXVlDgFisA=
|
||||
github.com/go-chi/chi v4.0.1+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
|
||||
github.com/go-chi/chi v4.0.2+incompatible h1:maB6vn6FqCxrpz4FqWdh4+lwpyZIQS7YEAUcHlgXVRs=
|
||||
github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
|
||||
github.com/go-chi/cors v1.0.0 h1:e6x8k7uWbUwYs+aXDoiUzeQFT6l0cygBYyNhD7/1Tg0=
|
||||
github.com/go-chi/cors v1.0.0/go.mod h1:K2Yje0VW/SJzxiyMYu6iPQYa7hMjQX2i/F491VChg1I=
|
||||
github.com/go-chi/render v1.0.1 h1:4/5tis2cKaNdnv9zFLfXzcquC9HbeZgCnxGnKrltBS8=
|
||||
@ -18,29 +18,32 @@ github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH
|
||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/miekg/dns v1.1.4 h1:rCMZsU2ScVSYcAsOXgmC6+AKOK+6pmQTOcw03nfwYV0=
|
||||
github.com/miekg/dns v1.1.4/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||
github.com/oschwald/geoip2-golang v1.2.1 h1:3iz+jmeJc6fuCyWeKgtXSXu7+zvkxJbHFXkMT5FVebU=
|
||||
github.com/oschwald/geoip2-golang v1.2.1/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
||||
github.com/oschwald/maxminddb-golang v1.3.0 h1:oTh8IBSj10S5JNlUDg5WjJ1QdBMdeaZIkPEVfESSWgE=
|
||||
github.com/oschwald/maxminddb-golang v1.3.0/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY=
|
||||
github.com/miekg/dns v1.1.14 h1:wkQWn9wIp4mZbwW8XV6Km6owkvRPbOiV004ZM2CkGvA=
|
||||
github.com/miekg/dns v1.1.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||
github.com/oschwald/geoip2-golang v1.3.0 h1:D+Hsdos1NARPbzZ2aInUHZL+dApIzo8E0ErJVsWcku8=
|
||||
github.com/oschwald/geoip2-golang v1.3.0/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
||||
github.com/oschwald/maxminddb-golang v1.3.1 h1:kPc5+ieL5CC/Zn0IaXJPxDFlUxKTQEU8QBTtmfQDAIo=
|
||||
github.com/oschwald/maxminddb-golang v1.3.1/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.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME=
|
||||
github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613 h1:MQ/ZZiDsUapFFiMS+vzwXkCTeEKaum+Do5rINYJDmxc=
|
||||
golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/net v0.0.0-20181108082009-03003ca0c849 h1:FSqE2GGG7wzsYUsWiQ8MZrvEd1EOyU3NCF0AW3Wtltg=
|
||||
golang.org/x/net v0.0.0-20181108082009-03003ca0c849/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181005133103-4497e2df6f9e h1:EfdBzeKbFSvOjoIqSZcfS8wp0FBLokGBEs9lz1OtSg0=
|
||||
golang.org/x/sys v0.0.0-20181005133103-4497e2df6f9e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734 h1:p/H982KKEjUnLJkM3tt/LemDnOc1GiZL5FCVlORJ5zo=
|
||||
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
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=
|
||||
|
@ -1,12 +1,13 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
||||
"github.com/Dreamacro/clash/component/auth"
|
||||
"github.com/Dreamacro/clash/config"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/dns"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
P "github.com/Dreamacro/clash/proxy"
|
||||
authStore "github.com/Dreamacro/clash/proxy/auth"
|
||||
T "github.com/Dreamacro/clash/tunnel"
|
||||
)
|
||||
|
||||
@ -22,29 +23,43 @@ func ParseWithPath(path string) (*config.Config, error) {
|
||||
|
||||
// ApplyConfig dispatch configure to all parts
|
||||
func ApplyConfig(cfg *config.Config, force bool) {
|
||||
updateUsers(cfg.Users)
|
||||
if force {
|
||||
updateGeneral(cfg.General)
|
||||
}
|
||||
updateProxies(cfg.Proxies)
|
||||
updateRules(cfg.Rules)
|
||||
updateDNS(cfg.DNS)
|
||||
updateExperimental(cfg.Experimental)
|
||||
}
|
||||
|
||||
func GetGeneral() *config.General {
|
||||
ports := P.GetPorts()
|
||||
return &config.General{
|
||||
Port: ports.Port,
|
||||
SocksPort: ports.SocksPort,
|
||||
RedirPort: ports.RedirPort,
|
||||
AllowLan: P.AllowLan(),
|
||||
Mode: T.Instance().Mode(),
|
||||
LogLevel: log.Level(),
|
||||
authenticator := []string{}
|
||||
if auth := authStore.Authenticator(); auth != nil {
|
||||
authenticator = auth.Users()
|
||||
}
|
||||
|
||||
general := &config.General{
|
||||
Port: ports.Port,
|
||||
SocksPort: ports.SocksPort,
|
||||
RedirPort: ports.RedirPort,
|
||||
Authentication: authenticator,
|
||||
AllowLan: P.AllowLan(),
|
||||
Mode: T.Instance().Mode(),
|
||||
LogLevel: log.Level(),
|
||||
}
|
||||
|
||||
return general
|
||||
}
|
||||
|
||||
func updateExperimental(c *config.Experimental) {
|
||||
T.Instance().UpdateExperimental(c.IgnoreResolveFail)
|
||||
}
|
||||
|
||||
func updateDNS(c *config.DNS) {
|
||||
if c.Enable == false {
|
||||
T.Instance().SetResolver(nil)
|
||||
dns.DefaultResolver = nil
|
||||
dns.ReCreateServer("", nil)
|
||||
return
|
||||
}
|
||||
@ -53,27 +68,26 @@ func updateDNS(c *config.DNS) {
|
||||
Fallback: c.Fallback,
|
||||
IPv6: c.IPv6,
|
||||
EnhancedMode: c.EnhancedMode,
|
||||
Pool: c.FakeIPRange,
|
||||
})
|
||||
T.Instance().SetResolver(r)
|
||||
dns.DefaultResolver = r
|
||||
if err := dns.ReCreateServer(c.Listen, r); err != nil {
|
||||
log.Errorln("Start DNS server error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
log.Infoln("DNS server listening at: %s", c.Listen)
|
||||
|
||||
if c.Listen != "" {
|
||||
log.Infoln("DNS server listening at: %s", c.Listen)
|
||||
}
|
||||
}
|
||||
|
||||
func updateProxies(proxies map[string]C.Proxy) {
|
||||
tunnel := T.Instance()
|
||||
oldProxies := tunnel.Proxies()
|
||||
|
||||
// close old goroutine
|
||||
// close proxy group goroutine
|
||||
for _, proxy := range oldProxies {
|
||||
switch raw := proxy.(type) {
|
||||
case *adapters.URLTest:
|
||||
raw.Close()
|
||||
case *adapters.Fallback:
|
||||
raw.Close()
|
||||
}
|
||||
proxy.Destroy()
|
||||
}
|
||||
|
||||
tunnel.UpdateProxies(proxies)
|
||||
@ -90,6 +104,7 @@ func updateGeneral(general *config.General) {
|
||||
allowLan := general.AllowLan
|
||||
|
||||
P.SetAllowLan(allowLan)
|
||||
|
||||
if err := P.ReCreateHTTP(general.Port); err != nil {
|
||||
log.Errorln("Start HTTP server error: %s", err.Error())
|
||||
}
|
||||
@ -102,3 +117,11 @@ func updateGeneral(general *config.General) {
|
||||
log.Errorln("Start Redir server error: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func updateUsers(users []auth.AuthUser) {
|
||||
authenticator := auth.NewAuthenticator(users)
|
||||
authStore.SetAuthenticator(authenticator)
|
||||
if authenticator != nil {
|
||||
log.Infoln("Authentication of local server updated")
|
||||
}
|
||||
}
|
||||
|
@ -59,7 +59,7 @@ func findProxyByName(next http.Handler) http.Handler {
|
||||
|
||||
func getProxies(w http.ResponseWriter, r *http.Request) {
|
||||
proxies := T.Instance().Proxies()
|
||||
render.JSON(w, r, map[string]map[string]C.Proxy{
|
||||
render.JSON(w, r, render.M{
|
||||
"proxies": proxies,
|
||||
})
|
||||
}
|
||||
@ -81,12 +81,11 @@ func updateProxy(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||
|
||||
selector, ok := proxy.(*A.Selector)
|
||||
proxy := r.Context().Value(CtxKeyProxy).(*A.Proxy)
|
||||
selector, ok := proxy.ProxyAdapter.(*A.Selector)
|
||||
if !ok {
|
||||
render.Status(r, http.StatusBadRequest)
|
||||
render.JSON(w, r, ErrBadRequest)
|
||||
render.JSON(w, r, newError("Must be a Selector"))
|
||||
return
|
||||
}
|
||||
|
||||
@ -111,9 +110,9 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
proxy := r.Context().Value(CtxKeyProxy).(C.Proxy)
|
||||
|
||||
sigCh := make(chan int16)
|
||||
sigCh := make(chan uint16)
|
||||
go func() {
|
||||
t, err := A.DelayTest(proxy, url)
|
||||
t, err := proxy.URLTest(url)
|
||||
if err != nil {
|
||||
sigCh <- 0
|
||||
}
|
||||
@ -129,7 +128,7 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) {
|
||||
render.Status(r, http.StatusServiceUnavailable)
|
||||
render.JSON(w, r, newError("An error occurred in the delay test"))
|
||||
} else {
|
||||
render.JSON(w, r, map[string]int16{
|
||||
render.JSON(w, r, render.M{
|
||||
"delay": t,
|
||||
})
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ type Rule struct {
|
||||
func getRules(w http.ResponseWriter, r *http.Request) {
|
||||
rawRules := T.Instance().Rules()
|
||||
|
||||
var rules []Rule
|
||||
rules := []Rule{}
|
||||
for _, rule := range rawRules {
|
||||
rules = append(rules, Rule{
|
||||
Type: rule.RuleType().String(),
|
||||
@ -33,7 +33,7 @@ func getRules(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
render.JSON(w, r, map[string][]Rule{
|
||||
render.JSON(w, r, render.M{
|
||||
"rules": rules,
|
||||
})
|
||||
}
|
||||
|
@ -2,6 +2,7 @@ package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/Dreamacro/clash/common/observable"
|
||||
|
||||
@ -15,6 +16,7 @@ var (
|
||||
)
|
||||
|
||||
func init() {
|
||||
log.SetOutput(os.Stdout)
|
||||
log.SetLevel(log.DebugLevel)
|
||||
}
|
||||
|
||||
|
12
main.go
12
main.go
@ -2,9 +2,11 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"syscall"
|
||||
|
||||
"github.com/Dreamacro/clash/config"
|
||||
@ -15,15 +17,25 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
version bool
|
||||
homedir string
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&homedir, "d", "", "set configuration directory")
|
||||
flag.BoolVar(&version, "v", false, "show current version of clash")
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
func main() {
|
||||
if version {
|
||||
fmt.Printf("Clash %s %s %s %s\n", C.Version, runtime.GOOS, runtime.GOARCH, C.BuildTime)
|
||||
return
|
||||
}
|
||||
|
||||
// enable tls 1.3 and remove when go 1.13
|
||||
os.Setenv("GODEBUG", os.Getenv("GODEBUG")+",tls13=1")
|
||||
|
||||
if homedir != "" {
|
||||
if !filepath.IsAbs(homedir) {
|
||||
currentDir, _ := os.Getwd()
|
||||
|
17
proxy/auth/auth.go
Normal file
17
proxy/auth/auth.go
Normal file
@ -0,0 +1,17 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/Dreamacro/clash/component/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
authenticator auth.Authenticator
|
||||
)
|
||||
|
||||
func Authenticator() auth.Authenticator {
|
||||
return authenticator
|
||||
}
|
||||
|
||||
func SetAuthenticator(au auth.Authenticator) {
|
||||
authenticator = au
|
||||
}
|
@ -2,11 +2,17 @@ package http
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/inbound"
|
||||
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"github.com/Dreamacro/clash/component/auth"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
authStore "github.com/Dreamacro/clash/proxy/auth"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
)
|
||||
|
||||
@ -18,6 +24,7 @@ type HttpListener struct {
|
||||
net.Listener
|
||||
address string
|
||||
closed bool
|
||||
cache *cache.Cache
|
||||
}
|
||||
|
||||
func NewHttpProxy(addr string) (*HttpListener, error) {
|
||||
@ -25,10 +32,11 @@ func NewHttpProxy(addr string) (*HttpListener, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hl := &HttpListener{l, addr, false}
|
||||
hl := &HttpListener{l, addr, false, cache.New(30 * time.Second)}
|
||||
|
||||
go func() {
|
||||
log.Infoln("HTTP proxy listening at: %s", addr)
|
||||
|
||||
for {
|
||||
c, err := hl.Accept()
|
||||
if err != nil {
|
||||
@ -37,7 +45,7 @@ func NewHttpProxy(addr string) (*HttpListener, error) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
go handleConn(c)
|
||||
go handleConn(c, hl.cache)
|
||||
}
|
||||
}()
|
||||
|
||||
@ -53,14 +61,40 @@ func (l *HttpListener) Address() string {
|
||||
return l.address
|
||||
}
|
||||
|
||||
func handleConn(conn net.Conn) {
|
||||
func canActivate(loginStr string, authenticator auth.Authenticator, cache *cache.Cache) (ret bool) {
|
||||
if result := cache.Get(loginStr); result != nil {
|
||||
ret = result.(bool)
|
||||
}
|
||||
loginData, err := base64.StdEncoding.DecodeString(loginStr)
|
||||
login := strings.Split(string(loginData), ":")
|
||||
ret = err == nil && len(login) == 2 && authenticator.Verify(login[0], login[1])
|
||||
|
||||
cache.Put(loginStr, ret, time.Minute)
|
||||
return
|
||||
}
|
||||
|
||||
func handleConn(conn net.Conn, cache *cache.Cache) {
|
||||
br := bufio.NewReader(conn)
|
||||
request, err := http.ReadRequest(br)
|
||||
if err != nil {
|
||||
if err != nil || request.URL.Host == "" {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
authenticator := authStore.Authenticator()
|
||||
if authenticator != nil {
|
||||
if authStrings := strings.Split(request.Header.Get("Proxy-Authorization"), " "); len(authStrings) != 2 {
|
||||
_, err = conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\n\r\n"))
|
||||
conn.Close()
|
||||
return
|
||||
} else if !canActivate(authStrings[1], authenticator, cache) {
|
||||
conn.Write([]byte("HTTP/1.1 403 Forbidden\r\n\r\n"))
|
||||
log.Infoln("Auth failed from %s", conn.RemoteAddr().String())
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if request.Method == http.MethodConnect {
|
||||
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||
if err != nil {
|
||||
|
@ -59,5 +59,5 @@ func handleRedir(conn net.Conn) {
|
||||
return
|
||||
}
|
||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||
tun.Add(adapters.NewSocket(target, conn, C.REDIR))
|
||||
tun.Add(adapters.NewSocket(target, conn, C.REDIR, C.TCP))
|
||||
}
|
||||
|
@ -5,10 +5,10 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
)
|
||||
|
||||
func parserPacket(c net.Conn) (socks.Addr, error) {
|
||||
func parserPacket(c net.Conn) (socks5.Addr, error) {
|
||||
const (
|
||||
PfInout = 0
|
||||
PfIn = 1
|
||||
@ -51,7 +51,7 @@ func parserPacket(c net.Conn) (socks.Addr, error) {
|
||||
}
|
||||
|
||||
addr := make([]byte, 1+net.IPv4len+2)
|
||||
addr[0] = socks.AtypIPv4
|
||||
addr[0] = socks5.AtypIPv4
|
||||
copy(addr[1:1+net.IPv4len], nl.rdaddr[:4])
|
||||
copy(addr[1+net.IPv4len:], nl.rdxport[:2])
|
||||
return addr, nil
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -14,7 +14,7 @@ const (
|
||||
IP6T_SO_ORIGINAL_DST = 80 // from linux/include/uapi/linux/netfilter_ipv6/ip6_tables.h
|
||||
)
|
||||
|
||||
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
func parserPacket(conn net.Conn) (socks5.Addr, error) {
|
||||
c, ok := conn.(*net.TCPConn)
|
||||
if !ok {
|
||||
return nil, errors.New("only work with TCP connection")
|
||||
@ -25,7 +25,7 @@ func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var addr socks.Addr
|
||||
var addr socks5.Addr
|
||||
|
||||
rc.Control(func(fd uintptr) {
|
||||
addr, err = getorigdst(fd)
|
||||
@ -35,7 +35,7 @@ func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
}
|
||||
|
||||
// Call getorigdst() from linux/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4.c
|
||||
func getorigdst(fd uintptr) (socks.Addr, error) {
|
||||
func getorigdst(fd uintptr) (socks5.Addr, error) {
|
||||
raw := syscall.RawSockaddrInet4{}
|
||||
siz := unsafe.Sizeof(raw)
|
||||
_, _, err := syscall.Syscall6(syscall.SYS_GETSOCKOPT, fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST, uintptr(unsafe.Pointer(&raw)), uintptr(unsafe.Pointer(&siz)), 0)
|
||||
@ -44,7 +44,7 @@ func getorigdst(fd uintptr) (socks.Addr, error) {
|
||||
}
|
||||
|
||||
addr := make([]byte, 1+net.IPv4len+2)
|
||||
addr[0] = socks.AtypIPv4
|
||||
addr[0] = socks5.AtypIPv4
|
||||
copy(addr[1:1+net.IPv4len], raw.Addr[:])
|
||||
port := (*[2]byte)(unsafe.Pointer(&raw.Port)) // big-endian
|
||||
addr[1+net.IPv4len], addr[1+net.IPv4len+1] = port[0], port[1]
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -14,7 +14,7 @@ const (
|
||||
IP6T_SO_ORIGINAL_DST = 80 // from linux/include/uapi/linux/netfilter_ipv6/ip6_tables.h
|
||||
)
|
||||
|
||||
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
func parserPacket(conn net.Conn) (socks5.Addr, error) {
|
||||
c, ok := conn.(*net.TCPConn)
|
||||
if !ok {
|
||||
return nil, errors.New("only work with TCP connection")
|
||||
@ -25,7 +25,7 @@ func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var addr socks.Addr
|
||||
var addr socks5.Addr
|
||||
|
||||
rc.Control(func(fd uintptr) {
|
||||
addr, err = getorigdst(fd)
|
||||
@ -35,7 +35,7 @@ func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
}
|
||||
|
||||
// Call getorigdst() from linux/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4.c
|
||||
func getorigdst(fd uintptr) (socks.Addr, error) {
|
||||
func getorigdst(fd uintptr) (socks5.Addr, error) {
|
||||
raw := syscall.RawSockaddrInet4{}
|
||||
siz := unsafe.Sizeof(raw)
|
||||
if err := socketcall(GETSOCKOPT, fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST, uintptr(unsafe.Pointer(&raw)), uintptr(unsafe.Pointer(&siz)), 0); err != nil {
|
||||
@ -43,7 +43,7 @@ func getorigdst(fd uintptr) (socks.Addr, error) {
|
||||
}
|
||||
|
||||
addr := make([]byte, 1+net.IPv4len+2)
|
||||
addr[0] = socks.AtypIPv4
|
||||
addr[0] = socks5.AtypIPv4
|
||||
copy(addr[1:1+net.IPv4len], raw.Addr[:])
|
||||
port := (*[2]byte)(unsafe.Pointer(&raw.Port)) // big-endian
|
||||
addr[1+net.IPv4len], addr[1+net.IPv4len+1] = port[0], port[1]
|
||||
|
@ -4,9 +4,9 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
)
|
||||
|
||||
func parserPacket(conn net.Conn) (socks.Addr, error) {
|
||||
func parserPacket(conn net.Conn) (socks5.Addr, error) {
|
||||
return nil, errors.New("Windows not support yet")
|
||||
}
|
||||
|
@ -3,12 +3,12 @@ package socks
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/adapters/inbound"
|
||||
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||
"github.com/Dreamacro/clash/component/socks5"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
authStore "github.com/Dreamacro/clash/proxy/auth"
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
|
||||
"github.com/Dreamacro/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -55,11 +55,15 @@ func (l *SockListener) Address() string {
|
||||
}
|
||||
|
||||
func handleSocks(conn net.Conn) {
|
||||
target, err := socks.Handshake(conn)
|
||||
target, command, err := socks5.ServerHandshake(conn, authStore.Authenticator())
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||
tun.Add(adapters.NewSocket(target, conn, C.SOCKS))
|
||||
if command == socks5.CmdUDPAssociate {
|
||||
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.UDP))
|
||||
return
|
||||
}
|
||||
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.TCP))
|
||||
}
|
||||
|
@ -1 +0,0 @@
|
||||
package socks
|
@ -4,28 +4,28 @@ import (
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type Final struct {
|
||||
type Match struct {
|
||||
adapter string
|
||||
}
|
||||
|
||||
func (f *Final) RuleType() C.RuleType {
|
||||
return C.FINAL
|
||||
func (f *Match) RuleType() C.RuleType {
|
||||
return C.MATCH
|
||||
}
|
||||
|
||||
func (f *Final) IsMatch(metadata *C.Metadata) bool {
|
||||
func (f *Match) IsMatch(metadata *C.Metadata) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (f *Final) Adapter() string {
|
||||
func (f *Match) Adapter() string {
|
||||
return f.adapter
|
||||
}
|
||||
|
||||
func (f *Final) Payload() string {
|
||||
func (f *Match) Payload() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func NewFinal(adapter string) *Final {
|
||||
return &Final{
|
||||
func NewMatch(adapter string) *Match {
|
||||
return &Match{
|
||||
adapter: adapter,
|
||||
}
|
||||
}
|
||||
|
@ -24,10 +24,10 @@ func (g *GEOIP) RuleType() C.RuleType {
|
||||
}
|
||||
|
||||
func (g *GEOIP) IsMatch(metadata *C.Metadata) bool {
|
||||
if metadata.IP == nil {
|
||||
if metadata.DstIP == nil {
|
||||
return false
|
||||
}
|
||||
record, _ := mmdb.Country(*metadata.IP)
|
||||
record, _ := mmdb.Country(*metadata.DstIP)
|
||||
return record.Country.IsoCode == g.country
|
||||
}
|
||||
|
||||
|
@ -14,17 +14,17 @@ type IPCIDR struct {
|
||||
|
||||
func (i *IPCIDR) RuleType() C.RuleType {
|
||||
if i.isSourceIP {
|
||||
return C.SourceIPCIDR
|
||||
return C.SrcIPCIDR
|
||||
}
|
||||
return C.IPCIDR
|
||||
}
|
||||
|
||||
func (i *IPCIDR) IsMatch(metadata *C.Metadata) bool {
|
||||
ip := metadata.IP
|
||||
ip := metadata.DstIP
|
||||
if i.isSourceIP {
|
||||
ip = metadata.SourceIP
|
||||
ip = metadata.SrcIP
|
||||
}
|
||||
return i.ipnet.Contains(*ip)
|
||||
return ip != nil && i.ipnet.Contains(*ip)
|
||||
}
|
||||
|
||||
func (i *IPCIDR) Adapter() string {
|
||||
@ -38,6 +38,7 @@ func (i *IPCIDR) Payload() string {
|
||||
func NewIPCIDR(s string, adapter string, isSourceIP bool) *IPCIDR {
|
||||
_, ipnet, err := net.ParseCIDR(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &IPCIDR{
|
||||
ipnet: ipnet,
|
||||
|
47
rules/port.go
Normal file
47
rules/port.go
Normal file
@ -0,0 +1,47 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
type Port struct {
|
||||
adapter string
|
||||
port string
|
||||
isSource bool
|
||||
}
|
||||
|
||||
func (p *Port) RuleType() C.RuleType {
|
||||
if p.isSource {
|
||||
return C.SrcPort
|
||||
}
|
||||
return C.DstPort
|
||||
}
|
||||
|
||||
func (p *Port) IsMatch(metadata *C.Metadata) bool {
|
||||
if p.isSource {
|
||||
return metadata.SrcPort == p.port
|
||||
}
|
||||
return metadata.DstPort == p.port
|
||||
}
|
||||
|
||||
func (p *Port) Adapter() string {
|
||||
return p.adapter
|
||||
}
|
||||
|
||||
func (p *Port) Payload() string {
|
||||
return p.port
|
||||
}
|
||||
|
||||
func NewPort(port string, adapter string, isSource bool) *Port {
|
||||
_, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &Port{
|
||||
adapter: adapter,
|
||||
port: port,
|
||||
isSource: isSource,
|
||||
}
|
||||
}
|
@ -6,31 +6,19 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
const (
|
||||
// io.Copy default buffer size is 32 KiB
|
||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||
bufferSize = 20 * 1024
|
||||
)
|
||||
|
||||
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, bufferSize) }}
|
||||
|
||||
func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
||||
conn := newTrafficTrack(outbound, t.traffic)
|
||||
req := request.R
|
||||
host := req.Host
|
||||
keepalive := true
|
||||
|
||||
for {
|
||||
if strings.ToLower(req.Header.Get("Connection")) == "close" {
|
||||
keepalive = false
|
||||
}
|
||||
keepAlive := strings.TrimSpace(strings.ToLower(req.Header.Get("Proxy-Connection"))) == "keep-alive"
|
||||
|
||||
req.Header.Set("Connection", "close")
|
||||
req.RequestURI = ""
|
||||
@ -53,16 +41,16 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
||||
} else {
|
||||
resp.Close = true
|
||||
}
|
||||
err = resp.Write(request.Conn())
|
||||
err = resp.Write(request)
|
||||
if err != nil || resp.Close {
|
||||
break
|
||||
}
|
||||
|
||||
if !keepalive {
|
||||
if !keepAlive {
|
||||
break
|
||||
}
|
||||
|
||||
req, err = http.ReadRequest(bufio.NewReader(request.Conn()))
|
||||
req, err = http.ReadRequest(bufio.NewReader(request))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
@ -75,9 +63,52 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Tunnel) handleSOCKS(request *adapters.SocketAdapter, outbound net.Conn) {
|
||||
func (t *Tunnel) handleSocket(request *adapters.SocketAdapter, outbound net.Conn) {
|
||||
conn := newTrafficTrack(outbound, t.traffic)
|
||||
relay(request.Conn(), conn)
|
||||
relay(request, conn)
|
||||
}
|
||||
|
||||
func (t *Tunnel) handleUDPOverTCP(conn net.Conn, pc net.PacketConn, addr net.Addr) error {
|
||||
ch := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
ch <- err
|
||||
return
|
||||
}
|
||||
pc.SetReadDeadline(time.Now().Add(120 * time.Second))
|
||||
if _, err = pc.WriteTo(buf[:n], addr); err != nil {
|
||||
ch <- err
|
||||
return
|
||||
}
|
||||
t.traffic.Up() <- int64(n)
|
||||
ch <- nil
|
||||
}
|
||||
}()
|
||||
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf)
|
||||
|
||||
for {
|
||||
pc.SetReadDeadline(time.Now().Add(120 * time.Second))
|
||||
n, _, err := pc.ReadFrom(buf)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
if _, err := conn.Write(buf[:n]); err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
t.traffic.Down() <- int64(n)
|
||||
}
|
||||
|
||||
<-ch
|
||||
return nil
|
||||
}
|
||||
|
||||
// relay copies between left and right bidirectionally.
|
||||
@ -85,16 +116,16 @@ func relay(leftConn, rightConn net.Conn) {
|
||||
ch := make(chan error)
|
||||
|
||||
go func() {
|
||||
buf := bufPool.Get().([]byte)
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
_, err := io.CopyBuffer(leftConn, rightConn, buf)
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
leftConn.SetReadDeadline(time.Now())
|
||||
ch <- err
|
||||
}()
|
||||
|
||||
buf := bufPool.Get().([]byte)
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
io.CopyBuffer(rightConn, leftConn, buf)
|
||||
bufPool.Put(buf[:cap(buf)])
|
||||
pool.BufPool.Put(buf[:cap(buf)])
|
||||
rightConn.SetReadDeadline(time.Now())
|
||||
<-ch
|
||||
}
|
||||
|
126
tunnel/tunnel.go
126
tunnel/tunnel.go
@ -19,14 +19,16 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// Tunnel handle proxy socket and HTTP/SOCKS socket
|
||||
// Tunnel handle relay inbound proxy and outbound proxy
|
||||
type Tunnel struct {
|
||||
queue *channels.InfiniteChannel
|
||||
rules []C.Rule
|
||||
proxies map[string]C.Proxy
|
||||
configLock *sync.RWMutex
|
||||
traffic *C.Traffic
|
||||
resolver *dns.Resolver
|
||||
queue *channels.InfiniteChannel
|
||||
rules []C.Rule
|
||||
proxies map[string]C.Proxy
|
||||
configMux *sync.RWMutex
|
||||
traffic *C.Traffic
|
||||
|
||||
// experimental features
|
||||
ignoreResolveFail bool
|
||||
|
||||
// Outbound Rule
|
||||
mode Mode
|
||||
@ -49,9 +51,9 @@ func (t *Tunnel) Rules() []C.Rule {
|
||||
|
||||
// UpdateRules handle update rules
|
||||
func (t *Tunnel) UpdateRules(rules []C.Rule) {
|
||||
t.configLock.Lock()
|
||||
t.configMux.Lock()
|
||||
t.rules = rules
|
||||
t.configLock.Unlock()
|
||||
t.configMux.Unlock()
|
||||
}
|
||||
|
||||
// Proxies return all proxies
|
||||
@ -61,9 +63,16 @@ func (t *Tunnel) Proxies() map[string]C.Proxy {
|
||||
|
||||
// UpdateProxies handle update proxies
|
||||
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy) {
|
||||
t.configLock.Lock()
|
||||
t.configMux.Lock()
|
||||
t.proxies = proxies
|
||||
t.configLock.Unlock()
|
||||
t.configMux.Unlock()
|
||||
}
|
||||
|
||||
// UpdateExperimental handle update experimental config
|
||||
func (t *Tunnel) UpdateExperimental(ignoreResolveFail bool) {
|
||||
t.configMux.Lock()
|
||||
t.ignoreResolveFail = ignoreResolveFail
|
||||
t.configMux.Unlock()
|
||||
}
|
||||
|
||||
// Mode return current mode
|
||||
@ -76,15 +85,6 @@ func (t *Tunnel) SetMode(mode Mode) {
|
||||
t.mode = mode
|
||||
}
|
||||
|
||||
// SetResolver change the resolver of tunnel
|
||||
func (t *Tunnel) SetResolver(resolver *dns.Resolver) {
|
||||
t.resolver = resolver
|
||||
}
|
||||
|
||||
func (t *Tunnel) hasResolver() bool {
|
||||
return t.resolver != nil
|
||||
}
|
||||
|
||||
func (t *Tunnel) process() {
|
||||
queue := t.queue.Out()
|
||||
for {
|
||||
@ -95,31 +95,31 @@ func (t *Tunnel) process() {
|
||||
}
|
||||
|
||||
func (t *Tunnel) resolveIP(host string) (net.IP, error) {
|
||||
if t.resolver == nil {
|
||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ipAddr.IP, nil
|
||||
}
|
||||
|
||||
return t.resolver.ResolveIP(host)
|
||||
return dns.ResolveIP(host)
|
||||
}
|
||||
|
||||
func (t *Tunnel) needLookupIP(metadata *C.Metadata) bool {
|
||||
return t.hasResolver() && t.resolver.IsMapping() && metadata.Host == "" && metadata.IP != nil
|
||||
return dns.DefaultResolver != nil && (dns.DefaultResolver.IsMapping() || dns.DefaultResolver.IsFakeIP()) && metadata.Host == "" && metadata.DstIP != nil
|
||||
}
|
||||
|
||||
func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
||||
defer localConn.Close()
|
||||
metadata := localConn.Metadata()
|
||||
|
||||
if !metadata.Valid() {
|
||||
log.Warnln("[Metadata] not valid: %#v", metadata)
|
||||
return
|
||||
}
|
||||
|
||||
// preprocess enhanced-mode metadata
|
||||
if t.needLookupIP(metadata) {
|
||||
host, exist := t.resolver.IPToHost(*metadata.IP)
|
||||
host, exist := dns.DefaultResolver.IPToHost(*metadata.DstIP)
|
||||
if exist {
|
||||
metadata.Host = host
|
||||
metadata.AddrType = C.AtypDomainName
|
||||
if dns.DefaultResolver.IsFakeIP() {
|
||||
metadata.DstIP = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -138,14 +138,21 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
||||
}
|
||||
}
|
||||
|
||||
if !metadata.Valid() {
|
||||
log.Warnln("[Metadata] not valid: %#v", metadata)
|
||||
if metadata.NetWork == C.UDP {
|
||||
pc, addr, err := proxy.DialUDP(metadata)
|
||||
if err != nil {
|
||||
log.Warnln("Proxy[%s] connect [%s --> %s] error: %s", proxy.Name(), metadata.SrcIP.String(), metadata.String(), err.Error())
|
||||
return
|
||||
}
|
||||
defer pc.Close()
|
||||
|
||||
t.handleUDPOverTCP(localConn, pc, addr)
|
||||
return
|
||||
}
|
||||
|
||||
remoConn, err := proxy.Generator(metadata)
|
||||
remoConn, err := proxy.Dial(metadata)
|
||||
if err != nil {
|
||||
log.Warnln("Proxy[%s] connect [%s --> %s] error: %s", proxy.Name(), metadata.SourceIP.String(), metadata.String(), err.Error())
|
||||
log.Warnln("Proxy[%s] connect [%s --> %s] error: %s", proxy.Name(), metadata.SrcIP.String(), metadata.String(), err.Error())
|
||||
return
|
||||
}
|
||||
defer remoConn.Close()
|
||||
@ -154,46 +161,59 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
|
||||
case *InboundAdapter.HTTPAdapter:
|
||||
t.handleHTTP(adapter, remoConn)
|
||||
case *InboundAdapter.SocketAdapter:
|
||||
t.handleSOCKS(adapter, remoConn)
|
||||
t.handleSocket(adapter, remoConn)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Tunnel) shouldResolveIP(rule C.Rule, metadata *C.Metadata) bool {
|
||||
return (rule.RuleType() == C.GEOIP || rule.RuleType() == C.IPCIDR) && metadata.Host != "" && metadata.IP == nil
|
||||
return (rule.RuleType() == C.GEOIP || rule.RuleType() == C.IPCIDR) && metadata.Host != "" && metadata.DstIP == nil
|
||||
}
|
||||
|
||||
func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, error) {
|
||||
t.configLock.RLock()
|
||||
defer t.configLock.RUnlock()
|
||||
t.configMux.RLock()
|
||||
defer t.configMux.RUnlock()
|
||||
|
||||
var resolved bool
|
||||
for _, rule := range t.rules {
|
||||
if t.shouldResolveIP(rule, metadata) {
|
||||
if !resolved && t.shouldResolveIP(rule, metadata) {
|
||||
ip, err := t.resolveIP(metadata.Host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
||||
if !t.ignoreResolveFail {
|
||||
return nil, fmt.Errorf("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
||||
}
|
||||
log.Debugln("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
||||
} else {
|
||||
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
|
||||
metadata.DstIP = &ip
|
||||
}
|
||||
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
|
||||
metadata.IP = &ip
|
||||
resolved = true
|
||||
}
|
||||
|
||||
if rule.IsMatch(metadata) {
|
||||
if a, ok := t.proxies[rule.Adapter()]; ok {
|
||||
log.Infoln("%s --> %v match %s using %s", metadata.SourceIP.String(), metadata.String(), rule.RuleType().String(), rule.Adapter())
|
||||
return a, nil
|
||||
adapter, ok := t.proxies[rule.Adapter()]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if metadata.NetWork == C.UDP && !adapter.SupportUDP() {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Infoln("%s --> %v match %s using %s", metadata.SrcIP.String(), metadata.String(), rule.RuleType().String(), rule.Adapter())
|
||||
return adapter, nil
|
||||
}
|
||||
}
|
||||
log.Infoln("%s --> %v doesn't match any rule using DIRECT", metadata.SourceIP.String(), metadata.String())
|
||||
log.Infoln("%s --> %v doesn't match any rule using DIRECT", metadata.SrcIP.String(), metadata.String())
|
||||
return t.proxies["DIRECT"], nil
|
||||
}
|
||||
|
||||
func newTunnel() *Tunnel {
|
||||
return &Tunnel{
|
||||
queue: channels.NewInfiniteChannel(),
|
||||
proxies: make(map[string]C.Proxy),
|
||||
configLock: &sync.RWMutex{},
|
||||
traffic: C.NewTraffic(time.Second),
|
||||
mode: Rule,
|
||||
queue: channels.NewInfiniteChannel(),
|
||||
proxies: make(map[string]C.Proxy),
|
||||
configMux: &sync.RWMutex{},
|
||||
traffic: C.NewTraffic(time.Second),
|
||||
mode: Rule,
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user