mihomo/adapters/shadowsocks.go

104 lines
2.2 KiB
Go
Raw Normal View History

2018-06-10 22:50:03 +08:00
package adapters
import (
"bytes"
"fmt"
"io"
"net"
"net/url"
"strconv"
C "github.com/Dreamacro/clash/constant"
"github.com/riobard/go-shadowsocks2/core"
"github.com/riobard/go-shadowsocks2/socks"
)
// ShadowsocksAdapter is a shadowsocks adapter
type ShadowsocksAdapter struct {
conn net.Conn
}
2018-06-14 01:00:58 +08:00
// ReadWriter is used to handle network traffic
func (ss *ShadowsocksAdapter) ReadWriter() io.ReadWriter {
2018-06-10 22:50:03 +08:00
return ss.conn
}
// Close is used to close connection
func (ss *ShadowsocksAdapter) Close() {
ss.conn.Close()
}
2018-06-14 01:00:58 +08:00
func (ss *ShadowsocksAdapter) Conn() net.Conn {
return ss.conn
}
2018-06-10 22:50:03 +08:00
type ShadowSocks struct {
server string
2018-06-16 21:34:13 +08:00
name string
cipher core.Cipher
2018-06-10 22:50:03 +08:00
}
2018-06-16 21:34:13 +08:00
func (ss *ShadowSocks) Name() string {
return ss.name
}
2018-06-10 22:50:03 +08:00
func (ss *ShadowSocks) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) {
c, err := net.Dial("tcp", ss.server)
if err != nil {
return nil, fmt.Errorf("%s connect error", ss.server)
}
c.(*net.TCPConn).SetKeepAlive(true)
c = ss.cipher.StreamConn(c)
2018-06-10 22:50:03 +08:00
_, err = c.Write(serializesSocksAddr(addr))
return &ShadowsocksAdapter{conn: c}, err
}
2018-06-16 21:34:13 +08:00
func NewShadowSocks(name string, ssURL string) (*ShadowSocks, error) {
var key []byte
2018-06-10 22:50:03 +08:00
server, cipher, password, _ := parseURL(ssURL)
ciph, err := core.PickCipher(cipher, key, password)
if err != nil {
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
2018-06-10 22:50:03 +08:00
}
return &ShadowSocks{
server: server,
2018-06-16 21:34:13 +08:00
name: name,
cipher: ciph,
}, nil
2018-06-10 22:50:03 +08:00
}
func parseURL(s string) (addr, cipher, password string, err error) {
u, err := url.Parse(s)
if err != nil {
return
}
addr = u.Host
if u.User != nil {
cipher = u.User.Username()
password, _ = u.User.Password()
}
return
}
func serializesSocksAddr(addr *C.Addr) []byte {
var buf [][]byte
aType := uint8(addr.AddrType)
p, _ := strconv.Atoi(addr.Port)
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
switch addr.AddrType {
case socks.AtypDomainName:
len := uint8(len(addr.Host))
host := []byte(addr.Host)
buf = [][]byte{[]byte{aType, len}, host, port}
case socks.AtypIPv4:
2018-06-11 18:36:39 +08:00
host := addr.IP.To4()
2018-06-10 22:50:03 +08:00
buf = [][]byte{[]byte{aType}, host, port}
case socks.AtypIPv6:
2018-06-11 18:36:39 +08:00
host := addr.IP.To16()
2018-06-10 22:50:03 +08:00
buf = [][]byte{[]byte{aType}, host, port}
}
return bytes.Join(buf, []byte(""))
}