add tunnel handler and connector

This commit is contained in:
ginuerzh
2023-10-15 15:39:25 +08:00
parent 033151a770
commit 497915f465
24 changed files with 1375 additions and 63 deletions

View File

@ -17,7 +17,7 @@ import (
// Bind implements connector.Binder.
func (c *relayConnector) Bind(ctx context.Context, conn net.Conn, network, address string, opts ...connector.BindOption) (net.Listener, error) {
if !c.md.tunnelID.IsZero() {
return c.bindTunnel(ctx, conn, network, c.options.Logger)
return c.bindTunnel(ctx, conn, network, address, c.options.Logger)
}
log := c.options.Logger.WithFields(map[string]any{
@ -43,12 +43,12 @@ func (c *relayConnector) Bind(ctx context.Context, conn net.Conn, network, addre
}
}
func (c *relayConnector) bindTunnel(ctx context.Context, conn net.Conn, network string, log logger.Logger) (net.Listener, error) {
addr, cid, err := c.initTunnel(conn, network)
func (c *relayConnector) bindTunnel(ctx context.Context, conn net.Conn, network, address string, log logger.Logger) (net.Listener, error) {
addr, cid, err := c.initTunnel(conn, network, address)
if err != nil {
return nil, err
}
log.Debugf("create tunnel %s connector %s/%s OK", c.md.tunnelID.String(), cid, network)
log.Infof("create tunnel on %s/%s OK, tunnel=%s, connector=%s", addr, network, c.md.tunnelID.String(), cid)
session, err := mux.ServerSession(conn)
if err != nil {
@ -63,7 +63,7 @@ func (c *relayConnector) bindTunnel(ctx context.Context, conn net.Conn, network
}, nil
}
func (c *relayConnector) initTunnel(conn net.Conn, network string) (addr net.Addr, cid relay.ConnectorID, err error) {
func (c *relayConnector) initTunnel(conn net.Conn, network, address string) (addr net.Addr, cid relay.ConnectorID, err error) {
req := relay.Request{
Version: relay.Version1,
Cmd: relay.CmdBind,
@ -81,9 +81,14 @@ func (c *relayConnector) initTunnel(conn net.Conn, network string) (addr net.Add
})
}
req.Features = append(req.Features, &relay.TunnelFeature{
ID: c.md.tunnelID.ID(),
})
af := &relay.AddrFeature{}
af.ParseFrom(address)
req.Features = append(req.Features, af,
&relay.TunnelFeature{
ID: c.md.tunnelID.ID(),
},
)
if _, err = req.WriteTo(conn); err != nil {
return
}
@ -103,7 +108,10 @@ func (c *relayConnector) initTunnel(conn net.Conn, network string) (addr net.Add
switch f.Type() {
case relay.FeatureAddr:
if feature, _ := f.(*relay.AddrFeature); feature != nil {
addr, err = net.ResolveTCPAddr("tcp", net.JoinHostPort(feature.Host, strconv.Itoa(int(feature.Port))))
addr = &bindAddr{
network: network,
addr: net.JoinHostPort(feature.Host, strconv.Itoa(int(feature.Port))),
}
}
case relay.FeatureTunnel:
if feature, _ := f.(*relay.TunnelFeature); feature != nil {

View File

@ -209,3 +209,16 @@ func (c *bindUDPConn) RemoteAddr() net.Addr {
func (c *bindUDPConn) Metadata() mdata.Metadata {
return c.md
}
type bindAddr struct {
network string
addr string
}
func (p *bindAddr) Network() string {
return p.network
}
func (p *bindAddr) String() string {
return p.addr
}

95
connector/tunnel/bind.go Normal file
View File

@ -0,0 +1,95 @@
package tunnel
import (
"context"
"fmt"
"net"
"strconv"
"github.com/go-gost/core/connector"
"github.com/go-gost/relay"
"github.com/go-gost/x/internal/util/mux"
)
// Bind implements connector.Binder.
func (c *tunnelConnector) Bind(ctx context.Context, conn net.Conn, network, address string, opts ...connector.BindOption) (net.Listener, error) {
log := c.options.Logger
addr, cid, err := c.initTunnel(conn, network, address)
if err != nil {
return nil, err
}
log.Infof("create tunnel on %s/%s OK, tunnel=%s, connector=%s", addr, network, c.md.tunnelID.String(), cid)
session, err := mux.ServerSession(conn)
if err != nil {
return nil, err
}
return &bindListener{
network: network,
addr: addr,
session: session,
logger: log,
}, nil
}
func (c *tunnelConnector) initTunnel(conn net.Conn, network, address string) (addr net.Addr, cid relay.ConnectorID, err error) {
req := relay.Request{
Version: relay.Version1,
Cmd: relay.CmdBind,
}
if network == "udp" {
req.Cmd |= relay.FUDP
}
if c.options.Auth != nil {
pwd, _ := c.options.Auth.Password()
req.Features = append(req.Features, &relay.UserAuthFeature{
Username: c.options.Auth.Username(),
Password: pwd,
})
}
af := &relay.AddrFeature{}
af.ParseFrom(address)
req.Features = append(req.Features, af,
&relay.TunnelFeature{
ID: c.md.tunnelID.ID(),
},
)
if _, err = req.WriteTo(conn); err != nil {
return
}
// first reply, bind status
resp := relay.Response{}
if _, err = resp.ReadFrom(conn); err != nil {
return
}
if resp.Status != relay.StatusOK {
err = fmt.Errorf("%d: create tunnel %s failed", resp.Status, c.md.tunnelID.String())
return
}
for _, f := range resp.Features {
switch f.Type() {
case relay.FeatureAddr:
if feature, _ := f.(*relay.AddrFeature); feature != nil {
addr = &bindAddr{
network: network,
addr: net.JoinHostPort(feature.Host, strconv.Itoa(int(feature.Port))),
}
}
case relay.FeatureTunnel:
if feature, _ := f.(*relay.TunnelFeature); feature != nil {
cid = relay.NewConnectorID(feature.ID[:])
}
}
}
return
}

224
connector/tunnel/conn.go Normal file
View File

@ -0,0 +1,224 @@
package tunnel
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"net"
"sync"
"github.com/go-gost/core/common/bufpool"
mdata "github.com/go-gost/core/metadata"
"github.com/go-gost/relay"
)
type tcpConn struct {
net.Conn
wbuf bytes.Buffer
once sync.Once
}
func (c *tcpConn) Read(b []byte) (n int, err error) {
c.once.Do(func() {
err = readResponse(c.Conn)
})
if err != nil {
return
}
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.Conn.Write(c.wbuf.Bytes())
c.wbuf.Reset()
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
_, err = io.ReadFull(c.Conn, bb[:])
if err != nil {
return
}
dlen := int(binary.BigEndian.Uint16(bb[:]))
if len(b) >= dlen {
return io.ReadFull(c.Conn, b[:dlen])
}
buf := bufpool.Get(dlen)
defer bufpool.Put(buf)
_, err = io.ReadFull(c.Conn, *buf)
n = copy(b, *buf)
return
}
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)
if c.wbuf.Len() > 0 {
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.wbuf.WriteTo(c.Conn)
return
}
var bb [2]byte
binary.BigEndian.PutUint16(bb[:], uint16(len(b)))
_, err = c.Conn.Write(bb[:])
if err != nil {
return
}
return c.Conn.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
md mdata.Metadata
}
func (c *bindConn) LocalAddr() net.Addr {
return c.localAddr
}
func (c *bindConn) RemoteAddr() net.Addr {
return c.remoteAddr
}
// Metadata implements metadata.Metadatable interface.
func (c *bindConn) Metadata() mdata.Metadata {
return c.md
}
type bindUDPConn struct {
net.Conn
localAddr net.Addr
remoteAddr net.Addr
md mdata.Metadata
}
func (c *bindUDPConn) Read(b []byte) (n int, err error) {
// 2-byte data length header
var bh [2]byte
_, err = io.ReadFull(c.Conn, bh[:])
if err != nil {
return
}
dlen := int(binary.BigEndian.Uint16(bh[:]))
if len(b) >= dlen {
n, err = io.ReadFull(c.Conn, b[:dlen])
return
}
buf := bufpool.Get(dlen)
defer bufpool.Put(buf)
_, err = io.ReadFull(c.Conn, *buf)
n = copy(b, *buf)
return
}
func (c *bindUDPConn) Write(b []byte) (n int, err error) {
if len(b) > math.MaxUint16 {
err = errors.New("write: data maximum exceeded")
return
}
// 2-byte data length header
var bh [2]byte
binary.BigEndian.PutUint16(bh[:], uint16(len(b)))
_, err = c.Conn.Write(bh[:])
if err != nil {
return
}
return c.Conn.Write(b)
}
func (c *bindUDPConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
addr = c.remoteAddr
n, err = c.Read(b)
return
}
func (c *bindUDPConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
return c.Write(b)
}
func (c *bindUDPConn) LocalAddr() net.Addr {
return c.localAddr
}
func (c *bindUDPConn) RemoteAddr() net.Addr {
return c.remoteAddr
}
// Metadata implements metadata.Metadatable interface.
func (c *bindUDPConn) Metadata() mdata.Metadata {
return c.md
}
type bindAddr struct {
network string
addr string
}
func (p *bindAddr) Network() string {
return p.network
}
func (p *bindAddr) String() string {
return p.addr
}

View File

@ -0,0 +1,102 @@
package tunnel
import (
"context"
"fmt"
"net"
"time"
"github.com/go-gost/core/connector"
md "github.com/go-gost/core/metadata"
"github.com/go-gost/relay"
"github.com/go-gost/x/registry"
)
func init() {
registry.ConnectorRegistry().Register("tunnel", NewConnector)
}
type tunnelConnector struct {
md metadata
options connector.Options
}
func NewConnector(opts ...connector.Option) connector.Connector {
options := connector.Options{}
for _, opt := range opts {
opt(&options)
}
return &tunnelConnector{
options: options,
}
}
func (c *tunnelConnector) Init(md md.Metadata) (err error) {
return c.parseMetadata(md)
}
func (c *tunnelConnector) Connect(ctx context.Context, conn net.Conn, network, address string, opts ...connector.ConnectOption) (net.Conn, error) {
log := c.options.Logger.WithFields(map[string]any{
"remote": conn.RemoteAddr().String(),
"local": conn.LocalAddr().String(),
"network": network,
"address": address,
})
log.Debugf("connect %s/%s", address, network)
if c.md.connectTimeout > 0 {
conn.SetDeadline(time.Now().Add(c.md.connectTimeout))
defer conn.SetDeadline(time.Time{})
}
req := relay.Request{
Version: relay.Version1,
Cmd: relay.CmdConnect,
}
if c.options.Auth != nil {
pwd, _ := c.options.Auth.Password()
req.Features = append(req.Features, &relay.UserAuthFeature{
Username: c.options.Auth.Username(),
Password: pwd,
})
}
if address != "" {
af := &relay.AddrFeature{}
if err := af.ParseFrom(address); err != nil {
return nil, err
}
req.Features = append(req.Features, af)
}
req.Features = append(req.Features, &relay.TunnelFeature{
ID: c.md.tunnelID.ID(),
})
switch network {
case "tcp", "tcp4", "tcp6", "unix", "serial":
cc := &tcpConn{
Conn: conn,
}
if _, err := req.WriteTo(&cc.wbuf); err != nil {
return nil, err
}
conn = cc
case "udp", "udp4", "udp6":
cc := &udpConn{
Conn: conn,
}
if _, err := req.WriteTo(&cc.wbuf); err != nil {
return nil, err
}
conn = cc
default:
err := fmt.Errorf("network %s is unsupported", network)
log.Error(err)
return nil, err
}
return conn, nil
}

View File

@ -0,0 +1,99 @@
package tunnel
import (
"fmt"
"net"
"strconv"
"github.com/go-gost/core/logger"
mdata "github.com/go-gost/core/metadata"
"github.com/go-gost/relay"
"github.com/go-gost/x/internal/util/mux"
mdx "github.com/go-gost/x/metadata"
)
type bindListener struct {
network string
addr net.Addr
session *mux.Session
logger logger.Logger
}
func (p *bindListener) 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()
p.logger.Errorf("get peer failed: %s", err)
return nil, err
}
return conn, nil
}
func (p *bindListener) 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, host string
// the first addr is the client address, the optional second addr is the target host address.
for _, f := range resp.Features {
if f.Type() == relay.FeatureAddr {
if fa, ok := f.(*relay.AddrFeature); ok {
v := net.JoinHostPort(fa.Host, strconv.Itoa(int(fa.Port)))
if address != "" {
host = v
} else {
address = v
}
}
}
}
raddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
var md mdata.Metadata
if host != "" {
md = mdx.NewMetadata(map[string]any{"host": host})
}
if p.network == "udp" {
return &bindUDPConn{
Conn: conn,
localAddr: p.addr,
remoteAddr: raddr,
md: md,
}, nil
}
cn := &bindConn{
Conn: conn,
localAddr: p.addr,
remoteAddr: raddr,
md: md,
}
return cn, nil
}
func (p *bindListener) Addr() net.Addr {
return p.addr
}
func (p *bindListener) Close() error {
return p.session.Close()
}

View File

@ -0,0 +1,42 @@
package tunnel
import (
"errors"
"time"
mdata "github.com/go-gost/core/metadata"
mdutil "github.com/go-gost/core/metadata/util"
"github.com/go-gost/relay"
"github.com/google/uuid"
)
var (
ErrInvalidTunnelID = errors.New("tunnel: invalid tunnel ID")
)
type metadata struct {
connectTimeout time.Duration
tunnelID relay.TunnelID
}
func (c *tunnelConnector) parseMetadata(md mdata.Metadata) (err error) {
const (
connectTimeout = "connectTimeout"
noDelay = "nodelay"
)
c.md.connectTimeout = mdutil.GetDuration(md, connectTimeout)
if s := mdutil.GetString(md, "tunnelID", "tunnel.id"); s != "" {
uuid, err := uuid.Parse(s)
if err != nil {
return err
}
c.md.tunnelID = relay.NewTunnelID(uuid[:])
}
if c.md.tunnelID.IsZero() {
return ErrInvalidTunnelID
}
return
}