Clash.Meta/transport/snell/snell.go

124 lines
2.3 KiB
Go
Raw Normal View History

2019-10-09 18:46:23 +08:00
package snell
import (
"encoding/binary"
"errors"
"fmt"
2019-10-09 18:46:23 +08:00
"io"
"net"
2021-09-20 21:02:18 +08:00
"github.com/Dreamacro/clash/common/pool"
2019-10-09 18:46:23 +08:00
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
)
const (
Version1 = 1
Version2 = 2
DefaultSnellVersion = Version1
)
const (
CommandPing byte = 0
CommandConnect byte = 1
CommandConnectV2 byte = 5
2019-10-09 18:46:23 +08:00
CommandTunnel byte = 0
CommandPong byte = 1
2019-10-09 18:46:23 +08:00
CommandError byte = 2
Version byte = 1
)
2021-10-10 23:44:09 +08:00
var endSignal = []byte{}
2019-10-09 18:46:23 +08:00
type Snell struct {
net.Conn
buffer [1]byte
reply bool
}
func (s *Snell) Read(b []byte) (int, error) {
if s.reply {
return s.Conn.Read(b)
}
s.reply = true
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
return 0, err
}
if s.buffer[0] == CommandTunnel {
return s.Conn.Read(b)
} else if s.buffer[0] != CommandError {
2020-08-25 22:19:59 +08:00
return 0, errors.New("command not support")
2019-10-09 18:46:23 +08:00
}
// CommandError
// 1 byte error code
2019-10-09 18:46:23 +08:00
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
return 0, err
}
errcode := int(s.buffer[0])
2019-10-09 18:46:23 +08:00
// 1 byte error message length
if _, err := io.ReadFull(s.Conn, s.buffer[:]); err != nil {
return 0, err
}
2019-10-09 18:46:23 +08:00
length := int(s.buffer[0])
msg := make([]byte, length)
if _, err := io.ReadFull(s.Conn, msg); err != nil {
return 0, err
}
return 0, fmt.Errorf("server reported code: %d, message: %s", errcode, string(msg))
2019-10-09 18:46:23 +08:00
}
func WriteHeader(conn net.Conn, host string, port uint, version int) error {
2021-09-20 21:02:18 +08:00
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
2019-10-09 18:46:23 +08:00
buf.WriteByte(Version)
if version == Version2 {
buf.WriteByte(CommandConnectV2)
} else {
buf.WriteByte(CommandConnect)
}
2019-10-09 18:46:23 +08:00
// clientID length & id
buf.WriteByte(0)
// host & port
buf.WriteByte(uint8(len(host)))
buf.WriteString(host)
binary.Write(buf, binary.BigEndian, uint16(port))
if _, err := conn.Write(buf.Bytes()); err != nil {
return err
}
return nil
}
// HalfClose works only on version2
func HalfClose(conn net.Conn) error {
if _, err := conn.Write(endSignal); err != nil {
return err
}
if s, ok := conn.(*Snell); ok {
s.reply = false
}
return nil
}
func StreamConn(conn net.Conn, psk []byte, version int) *Snell {
var cipher shadowaead.Cipher
if version == Version2 {
cipher = NewAES128GCM(psk)
} else {
cipher = NewChacha20Poly1305(psk)
}
2019-10-09 18:46:23 +08:00
return &Snell{Conn: shadowaead.NewConn(conn, cipher)}
}