add bind for relay

This commit is contained in:
ginuerzh
2021-11-25 17:29:54 +08:00
parent 98ef6c7492
commit 6daf0a4d0f
29 changed files with 600 additions and 352 deletions

131
pkg/connector/relay/bind.go Normal file
View File

@ -0,0 +1,131 @@
package relay
import (
"context"
"fmt"
"net"
"strconv"
"github.com/go-gost/gost/pkg/common/util/mux"
"github.com/go-gost/gost/pkg/common/util/socks"
"github.com/go-gost/gost/pkg/common/util/udp"
"github.com/go-gost/gost/pkg/connector"
"github.com/go-gost/relay"
)
// Bind implements connector.Binder.
func (c *relayConnector) Bind(ctx context.Context, conn net.Conn, network, address string, opts ...connector.BindOption) (net.Listener, error) {
c.logger = c.logger.WithFields(map[string]interface{}{
"network": network,
"address": address,
})
c.logger.Infof("bind on %s/%s", address, network)
options := connector.BindOptions{}
for _, opt := range opts {
opt(&options)
}
switch network {
case "tcp", "tcp4", "tcp6":
return c.bindTCP(ctx, conn, network, address)
case "udp", "udp4", "udp6":
return c.bindUDP(ctx, conn, network, address, &options)
default:
err := fmt.Errorf("network %s is unsupported", network)
c.logger.Error(err)
return nil, err
}
}
func (c *relayConnector) bindTCP(ctx context.Context, conn net.Conn, network, address string) (net.Listener, error) {
laddr, err := c.bind(conn, relay.BIND, network, address)
if err != nil {
return nil, err
}
session, err := mux.ServerSession(conn)
if err != nil {
return nil, err
}
return &tcpListener{
addr: laddr,
session: session,
logger: c.logger,
}, nil
}
func (c *relayConnector) bindUDP(ctx context.Context, conn net.Conn, network, address string, opts *connector.BindOptions) (net.Listener, error) {
laddr, err := c.bind(conn, relay.FUDP|relay.BIND, network, address)
if err != nil {
return nil, err
}
ln := udp.NewListener(
socks.UDPTunClientPacketConn(conn),
laddr,
opts.Backlog,
opts.UDPDataQueueSize, opts.UDPDataBufferSize,
opts.UDPConnTTL,
c.logger)
return ln, nil
}
func (c *relayConnector) bind(conn net.Conn, cmd uint8, network, address string) (net.Addr, error) {
req := relay.Request{
Version: relay.Version1,
Flags: cmd,
}
if c.md.user != nil {
pwd, _ := c.md.user.Password()
req.Features = append(req.Features, &relay.UserAuthFeature{
Username: c.md.user.Username(),
Password: pwd,
})
}
fa := &relay.AddrFeature{}
fa.ParseFrom(address)
req.Features = append(req.Features, fa)
if _, err := req.WriteTo(conn); err != nil {
return nil, err
}
// first reply, bind status
resp := relay.Response{}
if _, err := resp.ReadFrom(conn); err != nil {
return nil, err
}
if resp.Status != relay.StatusOK {
return nil, fmt.Errorf("bind on %s/%s failed", address, network)
}
var addr string
for _, f := range resp.Features {
if f.Type() == relay.FeatureAddr {
if fa, ok := f.(*relay.AddrFeature); ok {
addr = net.JoinHostPort(fa.Host, strconv.Itoa(int(fa.Port)))
}
}
}
var baddr net.Addr
var err error
switch network {
case "tcp", "tcp4", "tcp6":
baddr, err = net.ResolveTCPAddr(network, addr)
case "udp", "udp4", "udp6":
baddr, err = net.ResolveUDPAddr(network, addr)
default:
err = fmt.Errorf("unknown network %s", network)
}
if err != nil {
return nil, err
}
c.logger.Debugf("bind on %s/%s OK", baddr, baddr.Network())
return baddr, nil
}

View File

@ -6,45 +6,53 @@ import (
"errors"
"fmt"
"io"
"math"
"net"
"sync"
"github.com/go-gost/gost/pkg/logger"
"github.com/go-gost/relay"
)
type conn struct {
type tcpConn struct {
net.Conn
udp bool
wbuf bytes.Buffer
once sync.Once
headerSent bool
logger logger.Logger
wbuf bytes.Buffer
once sync.Once
}
func (c *conn) Read(b []byte) (n int, err error) {
func (c *tcpConn) Read(b []byte) (n int, err error) {
c.once.Do(func() {
resp := relay.Response{}
_, err = resp.ReadFrom(c.Conn)
if err != nil {
return
}
if resp.Version != relay.Version1 {
err = relay.ErrBadVersion
return
}
if resp.Status != relay.StatusOK {
err = fmt.Errorf("status %d", resp.Status)
return
}
err = readResponse(c.Conn)
})
if err != nil {
return
}
return c.Conn.Read(b)
}
if !c.udp {
return c.Conn.Read(b)
func (c *tcpConn) Write(b []byte) (n int, err error) {
n = len(b) // force byte length consistent
if c.wbuf.Len() > 0 {
c.wbuf.Write(b) // append the data to the cached header
_, err = c.wbuf.WriteTo(c.Conn)
return
}
_, err = c.Conn.Write(b)
return
}
type udpConn struct {
net.Conn
wbuf bytes.Buffer
once sync.Once
}
func (c *udpConn) Read(b []byte) (n int, err error) {
c.once.Do(func() {
err = readResponse(c.Conn)
})
if err != nil {
return
}
var bb [2]byte
@ -52,6 +60,7 @@ func (c *conn) Read(b []byte) (n int, err error) {
if err != nil {
return
}
dlen := int(binary.BigEndian.Uint16(bb[:]))
if len(b) >= dlen {
return io.ReadFull(c.Conn, b[:dlen])
@ -59,59 +68,64 @@ func (c *conn) Read(b []byte) (n int, err error) {
buf := make([]byte, dlen)
_, err = io.ReadFull(c.Conn, buf)
n = copy(b, buf)
return
}
func (c *conn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
n, err = c.Read(b)
addr = c.Conn.RemoteAddr()
return
}
func (c *conn) Write(b []byte) (n int, err error) {
if len(b) > 0xFFFF {
func (c *udpConn) Write(b []byte) (n int, err error) {
if len(b) > math.MaxUint16 {
err = errors.New("write: data maximum exceeded")
return
}
n = len(b) // force byte length consistent
n = len(b)
if c.wbuf.Len() > 0 {
if c.udp {
var bb [2]byte
binary.BigEndian.PutUint16(bb[:2], uint16(len(b)))
c.wbuf.Write(bb[:])
c.headerSent = true
}
var bb [2]byte
binary.BigEndian.PutUint16(bb[:], uint16(len(b)))
c.wbuf.Write(bb[:])
c.wbuf.Write(b) // append the data to the cached header
// _, err = c.Conn.Write(c.wbuf.Bytes())
// c.wbuf.Reset()
_, err = c.wbuf.WriteTo(c.Conn)
return
}
if !c.udp {
return c.Conn.Write(b)
}
if !c.headerSent {
c.headerSent = true
b2 := make([]byte, len(b)+2)
copy(b2, b)
_, err = c.Conn.Write(b2)
var bb [2]byte
binary.BigEndian.PutUint16(bb[:], uint16(len(b)))
_, err = c.Conn.Write(bb[:])
if err != nil {
return
}
nsize := 2 + len(b)
var buf []byte
if nsize <= mediumBufferSize {
buf = mPool.Get().([]byte)
defer mPool.Put(buf)
} else {
buf = make([]byte, nsize)
}
binary.BigEndian.PutUint16(buf[:2], uint16(len(b)))
n = copy(buf[2:], b)
_, err = c.Conn.Write(buf[:nsize])
return
return c.Conn.Write(b)
}
func (c *relayConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
return c.Write(b)
func readResponse(r io.Reader) (err error) {
resp := relay.Response{}
_, err = resp.ReadFrom(r)
if err != nil {
return
}
if resp.Version != relay.Version1 {
err = relay.ErrBadVersion
return
}
if resp.Status != relay.StatusOK {
err = fmt.Errorf("status %d", resp.Status)
return
}
return nil
}
type bindConn struct {
net.Conn
localAddr net.Addr
remoteAddr net.Addr
}
func (c *bindConn) LocalAddr() net.Addr {
return c.localAddr
}
func (c *bindConn) RemoteAddr() net.Addr {
return c.remoteAddr
}

View File

@ -2,9 +2,11 @@ package relay
import (
"context"
"fmt"
"net"
"time"
"github.com/go-gost/gost/pkg/common/util/socks"
"github.com/go-gost/gost/pkg/connector"
"github.com/go-gost/gost/pkg/logger"
md "github.com/go-gost/gost/pkg/metadata"
@ -43,23 +45,30 @@ func (c *relayConnector) Connect(ctx context.Context, conn net.Conn, network, ad
"network": network,
"address": address,
})
c.logger.Infof("connect: %s/%s", address, network)
c.logger.Infof("connect %s/%s", address, network)
if c.md.connectTimeout > 0 {
conn.SetDeadline(time.Now().Add(c.md.connectTimeout))
defer conn.SetDeadline(time.Time{})
}
var udpMode bool
if network == "udp" || network == "udp4" || network == "udp6" {
udpMode = true
}
req := relay.Request{
Version: relay.Version1,
Flags: relay.CONNECT,
}
if udpMode {
if network == "udp" || network == "udp4" || network == "udp6" {
req.Flags |= relay.FUDP
// UDP association
if address == "" {
baddr, err := c.bind(conn, relay.FUDP|relay.BIND, network, address)
if err != nil {
return nil, err
}
c.logger.Debugf("associate on %s OK", baddr)
return socks.UDPTunClientConn(conn, nil), nil
}
}
if c.md.user != nil {
@ -76,7 +85,43 @@ func (c *relayConnector) Connect(ctx context.Context, conn net.Conn, network, ad
return nil, err
}
req.Features = append(req.Features, af)
// forward mode if port is 0.
if af.Port > 0 {
req.Features = append(req.Features, af)
}
}
if c.md.noDelay {
if _, err := req.WriteTo(conn); err != nil {
return nil, err
}
}
switch network {
case "tcp", "tcp4", "tcp6":
cc := &tcpConn{
Conn: conn,
}
if !c.md.noDelay {
if _, err := req.WriteTo(&cc.wbuf); err != nil {
return nil, err
}
}
conn = cc
case "udp", "udp4", "udp6":
cc := &udpConn{
Conn: conn,
}
if !c.md.noDelay {
if _, err := req.WriteTo(&cc.wbuf); err != nil {
return nil, err
}
}
conn = cc
default:
err := fmt.Errorf("network %s is unsupported", network)
c.logger.Error(err)
return nil, err
}
return conn, nil

View File

@ -0,0 +1,73 @@
package relay
import (
"fmt"
"net"
"strconv"
"github.com/go-gost/gost/pkg/common/util/mux"
"github.com/go-gost/gost/pkg/logger"
"github.com/go-gost/relay"
)
type tcpListener struct {
addr net.Addr
session *mux.Session
logger logger.Logger
}
func (p *tcpListener) Accept() (net.Conn, error) {
cc, err := p.session.Accept()
if err != nil {
return nil, err
}
conn, err := p.getPeerConn(cc)
if err != nil {
cc.Close()
return nil, err
}
return conn, nil
}
func (p *tcpListener) getPeerConn(conn net.Conn) (net.Conn, error) {
// second reply, peer connected
resp := relay.Response{}
if _, err := resp.ReadFrom(conn); err != nil {
return nil, err
}
if resp.Status != relay.StatusOK {
err := fmt.Errorf("peer connect failed")
return nil, err
}
var address string
for _, f := range resp.Features {
if f.Type() == relay.FeatureAddr {
if fa, ok := f.(*relay.AddrFeature); ok {
address = net.JoinHostPort(fa.Host, strconv.Itoa(int(fa.Port)))
}
}
}
raddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
return &bindConn{
Conn: conn,
localAddr: p.addr,
remoteAddr: raddr,
}, nil
}
func (p *tcpListener) Addr() net.Addr {
return p.addr
}
func (p *tcpListener) Close() error {
return p.session.Close()
}

View File

@ -11,14 +11,14 @@ import (
type metadata struct {
connectTimeout time.Duration
user *url.Userinfo
nodelay bool
noDelay bool
}
func (c *relayConnector) parseMetadata(md md.Metadata) (err error) {
const (
user = "user"
connectTimeout = "connectTimeout"
nodelay = "nodelay"
noDelay = "nodelay"
)
if v := md.GetString(user); v != "" {
@ -30,7 +30,7 @@ func (c *relayConnector) parseMetadata(md md.Metadata) (err error) {
}
}
c.md.connectTimeout = md.GetDuration(connectTimeout)
c.md.nodelay = md.GetBool(nodelay)
c.md.noDelay = md.GetBool(noDelay)
return
}