relay: added private tunnel

This commit is contained in:
ginuerzh
2023-01-29 11:55:26 +08:00
parent 93b40f4c86
commit 24037aba7b
11 changed files with 174 additions and 59 deletions

View File

@ -11,7 +11,6 @@ import (
"github.com/go-gost/core/chain"
"github.com/go-gost/core/handler"
md "github.com/go-gost/core/metadata"
xchain "github.com/go-gost/x/chain"
netpkg "github.com/go-gost/x/internal/net"
"github.com/go-gost/x/internal/util/forward"
"github.com/go-gost/x/registry"
@ -46,13 +45,6 @@ func (h *forwardHandler) Init(md md.Metadata) (err error) {
return
}
if h.hop == nil {
// dummy node used by relay connector.
h.hop = xchain.NewChainHop([]*chain.Node{
{Name: "dummy", Addr: ":0"},
})
}
h.router = h.options.Router
if h.router == nil {
h.router = chain.NewRouter(chain.LoggerRouterOption(h.options.Logger))
@ -101,17 +93,22 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn, opts ...hand
}
}
var target *chain.Node
if _, _, err := net.SplitHostPort(host); err != nil {
host = net.JoinHostPort(host, "0")
}
target := &chain.Node{
Addr: host,
}
if h.hop != nil {
target = h.hop.Select(ctx,
chain.HostSelectOption(host),
chain.ProtocolSelectOption(protocol),
)
}
if target == nil {
err := errors.New("target not available")
log.Error(err)
return err
if target == nil {
err := errors.New("target not available")
log.Error(err)
return err
}
}
log = log.WithFields(map[string]any{

View File

@ -212,8 +212,7 @@ func (h *relayHandler) handleTunnel(ctx context.Context, conn net.Conn, tunnelID
return
}
var connectorID relay.ConnectorID
copy(connectorID[:], uuid[:])
connectorID := relay.NewTunnelID(uuid[:])
af := &relay.AddrFeature{}
err = af.ParseFrom(h.ep.Addr().String())

View File

@ -10,6 +10,7 @@ import (
"github.com/go-gost/core/logger"
"github.com/go-gost/relay"
netpkg "github.com/go-gost/x/internal/net"
xnet "github.com/go-gost/x/internal/net"
sx "github.com/go-gost/x/internal/util/selector"
)
@ -19,7 +20,7 @@ func (h *relayHandler) handleConnect(ctx context.Context, conn net.Conn, network
"cmd": "connect",
})
log.Debugf("%s >> %s", conn.RemoteAddr(), address)
log.Debugf("%s >> %s/%s", conn.RemoteAddr(), address, network)
resp := relay.Response{
Version: relay.Version1,
@ -94,3 +95,83 @@ func (h *relayHandler) handleConnect(ctx context.Context, conn net.Conn, network
return nil
}
func (h *relayHandler) handleConnectTunnel(ctx context.Context, conn net.Conn, network, address string, tunnelID relay.TunnelID, log logger.Logger) error {
log = log.WithFields(map[string]any{
"dst": fmt.Sprintf("%s/%s", address, network),
"cmd": "connect",
"tunnel": tunnelID.String(),
})
log.Debugf("%s >> %s/%s", conn.RemoteAddr(), address, network)
resp := relay.Response{
Version: relay.Version1,
Status: relay.StatusOK,
}
host, _, _ := net.SplitHostPort(address)
if h.options.Bypass != nil && h.options.Bypass.Contains(address) {
log.Debug("bypass: ", address)
resp.Status = relay.StatusForbidden
_, err := resp.WriteTo(conn)
return err
}
var tid relay.TunnelID
if ingress := h.md.ingress; ingress != nil {
tid = parseTunnelID(ingress.Get(host))
}
if !tid.Equal(tunnelID) {
resp.Status = relay.StatusBadRequest
resp.WriteTo(conn)
err := fmt.Errorf("tunnel %s not found", tunnelID.String())
log.Error(err)
return err
}
cc, err := getTunnelConn(h.pool, tunnelID, 3, log)
if err != nil {
log.Error(err)
return err
}
defer cc.Close()
log.Debugf("%s >> %s", conn.RemoteAddr(), cc.RemoteAddr())
if h.md.noDelay {
if _, err := resp.WriteTo(conn); err != nil {
log.Error(err)
return err
}
} else {
rc := &tcpConn{
Conn: conn,
}
// cache the header
if _, err := resp.WriteTo(&rc.wbuf); err != nil {
return err
}
conn = rc
}
af := &relay.AddrFeature{}
af.ParseFrom(conn.RemoteAddr().String())
resp = relay.Response{
Version: relay.Version1,
Status: relay.StatusOK,
Features: []relay.Feature{af},
}
resp.WriteTo(cc)
t := time.Now()
log.Debugf("%s <-> %s", conn.RemoteAddr(), cc.RemoteAddr())
xnet.Transport(conn, cc)
log.WithFields(map[string]any{
"duration": time.Since(t),
}).Debugf("%s >-< %s", conn.RemoteAddr(), cc.RemoteAddr())
return nil
}

View File

@ -19,7 +19,6 @@ import (
climiter "github.com/go-gost/x/limiter/conn/wrapper"
limiter "github.com/go-gost/x/limiter/traffic/wrapper"
metrics "github.com/go-gost/x/metrics/wrapper"
"github.com/google/uuid"
)
type epListener struct {
@ -118,30 +117,18 @@ func (h *epHandler) Handle(ctx context.Context, conn net.Conn, opts ...handler.H
var tunnelID relay.TunnelID
if h.ingress != nil {
v := h.ingress.Get(host)
uuid, _ := uuid.Parse(v)
copy(tunnelID[:], uuid[:])
tunnelID = parseTunnelID(h.ingress.Get(host))
}
if tunnelID.IsPrivate() {
err := fmt.Errorf("tunnel %s is private", tunnelID)
log.Error(err)
return err
}
log = log.WithFields(map[string]any{
"tunnel": tunnelID.String(),
})
var cc net.Conn
var err error
for i := 0; i < 3; i++ {
c := h.pool.Get(tunnelID)
if c == nil {
err = fmt.Errorf("tunnel %s not available", tunnelID.String())
break
}
cc, err = c.Session().GetConn()
if err != nil {
log.Error(err)
continue
}
break
}
cc, err := getTunnelConn(h.pool, tunnelID, 3, log)
if err != nil {
log.Error(err)
return err

View File

@ -195,18 +195,23 @@ func (h *relayHandler) Handle(ctx context.Context, conn net.Conn, opts ...handle
}
if h.hop != nil {
if address != "" {
resp.Status = relay.StatusForbidden
log.Error("forward mode, connect is forbidden")
_, err := resp.WriteTo(conn)
return err
}
/*
if address != "" {
resp.Status = relay.StatusForbidden
log.Error("forward mode, CONNECT method is forbidden")
_, err := resp.WriteTo(conn)
return err
}
*/
// forward mode
return h.handleForward(ctx, conn, network, log)
}
switch req.Cmd & relay.CmdMask {
case 0, relay.CmdConnect:
case relay.CmdConnect:
if !tunnelID.IsZero() {
return h.handleConnectTunnel(ctx, conn, network, address, tunnelID, log)
}
return h.handleConnect(ctx, conn, network, address, log)
case relay.CmdBind:
if !tunnelID.IsZero() {

View File

@ -1,6 +1,8 @@
package relay
import (
"fmt"
"net"
"sync"
"sync/atomic"
"time"
@ -8,6 +10,7 @@ import (
"github.com/go-gost/core/logger"
"github.com/go-gost/relay"
"github.com/go-gost/x/internal/util/mux"
"github.com/google/uuid"
)
type Connector struct {
@ -110,13 +113,13 @@ func (t *Tunnel) clean() {
}
type ConnectorPool struct {
tunnels map[relay.TunnelID]*Tunnel
tunnels map[string]*Tunnel
mu sync.RWMutex
}
func NewConnectorPool() *ConnectorPool {
return &ConnectorPool{
tunnels: make(map[relay.TunnelID]*Tunnel),
tunnels: make(map[string]*Tunnel),
}
}
@ -124,10 +127,12 @@ func (p *ConnectorPool) Add(tid relay.TunnelID, c *Connector) {
p.mu.Lock()
defer p.mu.Unlock()
t := p.tunnels[tid]
s := tid.String()
t := p.tunnels[s]
if t == nil {
t = NewTunnel(tid)
p.tunnels[tid] = t
p.tunnels[s] = t
}
t.AddConnector(c)
}
@ -140,10 +145,49 @@ func (p *ConnectorPool) Get(tid relay.TunnelID) *Connector {
p.mu.RLock()
defer p.mu.RUnlock()
t := p.tunnels[tid]
t := p.tunnels[tid.String()]
if t == nil {
return nil
}
return t.GetConnector()
}
func parseTunnelID(s string) (tid relay.TunnelID) {
if s == "" {
return
}
private := false
if s[0] == '$' {
private = true
s = s[1:]
}
uuid, _ := uuid.Parse(s)
if private {
return relay.NewPrivateTunnelID(uuid[:])
}
return relay.NewTunnelID(uuid[:])
}
func getTunnelConn(pool *ConnectorPool, tunnelID relay.TunnelID, retry int, log logger.Logger) (conn net.Conn, err error) {
if retry <= 0 {
retry = 1
}
for i := 0; i < retry; i++ {
c := pool.Get(tunnelID)
if c == nil {
err = fmt.Errorf("tunnel %s not available", tunnelID.String())
break
}
conn, err = c.Session().GetConn()
if err != nil {
log.Error(err)
continue
}
break
}
return
}