2018-08-12 05:50:54 +00:00
|
|
|
package adapters
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
|
2018-09-21 07:27:51 +00:00
|
|
|
"github.com/Dreamacro/go-shadowsocks2/socks"
|
2018-08-12 05:50:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Socks5Adapter is a shadowsocks adapter
|
|
|
|
type Socks5Adapter struct {
|
|
|
|
conn net.Conn
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close is used to close connection
|
|
|
|
func (ss *Socks5Adapter) Close() {
|
|
|
|
ss.conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ss *Socks5Adapter) Conn() net.Conn {
|
|
|
|
return ss.conn
|
|
|
|
}
|
|
|
|
|
|
|
|
type Socks5 struct {
|
|
|
|
addr string
|
|
|
|
name string
|
|
|
|
}
|
|
|
|
|
2018-10-02 07:26:36 +00:00
|
|
|
type Socks5Option struct {
|
|
|
|
Name string `proxy:"name"`
|
|
|
|
Server string `proxy:"server"`
|
|
|
|
Port int `proxy:"port"`
|
|
|
|
}
|
|
|
|
|
2018-08-12 05:50:54 +00:00
|
|
|
func (ss *Socks5) Name() string {
|
|
|
|
return ss.name
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ss *Socks5) Type() C.AdapterType {
|
|
|
|
return C.Socks5
|
|
|
|
}
|
|
|
|
|
2018-09-30 04:25:52 +00:00
|
|
|
func (ss *Socks5) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
|
2018-08-12 05:50:54 +00:00
|
|
|
c, err := net.Dial("tcp", ss.addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("%s connect error", ss.addr)
|
|
|
|
}
|
2018-08-29 07:00:12 +00:00
|
|
|
tcpKeepAlive(c)
|
2018-09-30 04:25:52 +00:00
|
|
|
if err := ss.shakeHand(metadata, c); err != nil {
|
2018-08-12 05:50:54 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &Socks5Adapter{conn: c}, nil
|
|
|
|
}
|
|
|
|
|
2018-09-30 04:25:52 +00:00
|
|
|
func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
2018-08-12 05:50:54 +00:00
|
|
|
buf := make([]byte, socks.MaxAddrLen)
|
|
|
|
|
|
|
|
// VER, CMD, RSV
|
|
|
|
_, err := rw.Write([]byte{5, 1, 0})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if buf[0] != 5 {
|
|
|
|
return errors.New("SOCKS version error")
|
|
|
|
} else if buf[1] != 0 {
|
|
|
|
return errors.New("SOCKS need auth")
|
|
|
|
}
|
|
|
|
|
|
|
|
// VER, CMD, RSV, ADDR
|
2018-09-30 04:25:52 +00:00
|
|
|
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
|
2018-08-12 05:50:54 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-02 07:26:36 +00:00
|
|
|
func NewSocks5(option Socks5Option) *Socks5 {
|
2018-08-12 05:50:54 +00:00
|
|
|
return &Socks5{
|
2018-10-02 07:26:36 +00:00
|
|
|
addr: fmt.Sprintf("%s:%d", option.Server, option.Port),
|
|
|
|
name: option.Name,
|
2018-08-12 05:50:54 +00:00
|
|
|
}
|
|
|
|
}
|