initial commit
This commit is contained in:
193
handler/relay/bind.go
Normal file
193
handler/relay/bind.go
Normal file
@ -0,0 +1,193 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
netpkg "github.com/go-gost/gost/v3/pkg/common/net"
|
||||
net_relay "github.com/go-gost/gost/v3/pkg/common/net/relay"
|
||||
"github.com/go-gost/gost/v3/pkg/logger"
|
||||
"github.com/go-gost/relay"
|
||||
"github.com/go-gost/x/internal/util/mux"
|
||||
relay_util "github.com/go-gost/x/internal/util/relay"
|
||||
)
|
||||
|
||||
func (h *relayHandler) handleBind(ctx context.Context, conn net.Conn, network, address string, log logger.Logger) error {
|
||||
log = log.WithFields(map[string]any{
|
||||
"dst": fmt.Sprintf("%s/%s", address, network),
|
||||
"cmd": "bind",
|
||||
})
|
||||
|
||||
log.Infof("%s >> %s", conn.RemoteAddr(), address)
|
||||
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
}
|
||||
|
||||
if !h.md.enableBind {
|
||||
resp.Status = relay.StatusForbidden
|
||||
log.Error("relay: BIND is disabled")
|
||||
_, err := resp.WriteTo(conn)
|
||||
return err
|
||||
}
|
||||
|
||||
if network == "tcp" {
|
||||
return h.bindTCP(ctx, conn, network, address, log)
|
||||
} else {
|
||||
return h.bindUDP(ctx, conn, network, address, log)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *relayHandler) bindTCP(ctx context.Context, conn net.Conn, network, address string, log logger.Logger) error {
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
}
|
||||
|
||||
ln, err := net.Listen(network, address) // strict mode: if the port already in use, it will return error
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
resp.Status = relay.StatusServiceUnavailable
|
||||
resp.WriteTo(conn)
|
||||
return err
|
||||
}
|
||||
|
||||
af := &relay.AddrFeature{}
|
||||
err = af.ParseFrom(ln.Addr().String())
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
|
||||
// Issue: may not reachable when host has multi-interface
|
||||
af.Host, _, _ = net.SplitHostPort(conn.LocalAddr().String())
|
||||
af.AType = relay.AddrIPv4
|
||||
resp.Features = append(resp.Features, af)
|
||||
if _, err := resp.WriteTo(conn); err != nil {
|
||||
log.Error(err)
|
||||
ln.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
log = log.WithFields(map[string]any{
|
||||
"bind": fmt.Sprintf("%s/%s", ln.Addr(), ln.Addr().Network()),
|
||||
})
|
||||
log.Debugf("bind on %s OK", ln.Addr())
|
||||
|
||||
return h.serveTCPBind(ctx, conn, ln, log)
|
||||
}
|
||||
|
||||
func (h *relayHandler) bindUDP(ctx context.Context, conn net.Conn, network, address string, log logger.Logger) error {
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
}
|
||||
|
||||
bindAddr, _ := net.ResolveUDPAddr(network, address)
|
||||
pc, err := net.ListenUDP(network, bindAddr)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
defer pc.Close()
|
||||
|
||||
af := &relay.AddrFeature{}
|
||||
err = af.ParseFrom(pc.LocalAddr().String())
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
|
||||
// Issue: may not reachable when host has multi-interface
|
||||
af.Host, _, _ = net.SplitHostPort(conn.LocalAddr().String())
|
||||
af.AType = relay.AddrIPv4
|
||||
resp.Features = append(resp.Features, af)
|
||||
if _, err := resp.WriteTo(conn); err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
log = log.WithFields(map[string]any{
|
||||
"bind": pc.LocalAddr().String(),
|
||||
})
|
||||
log.Debugf("bind on %s OK", pc.LocalAddr())
|
||||
|
||||
r := net_relay.NewUDPRelay(relay_util.UDPTunServerConn(conn), pc).
|
||||
WithBypass(h.options.Bypass).
|
||||
WithLogger(log)
|
||||
r.SetBufferSize(h.md.udpBufferSize)
|
||||
|
||||
t := time.Now()
|
||||
log.Infof("%s <-> %s", conn.RemoteAddr(), pc.LocalAddr())
|
||||
r.Run()
|
||||
log.WithFields(map[string]any{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.RemoteAddr(), pc.LocalAddr())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *relayHandler) serveTCPBind(ctx context.Context, conn net.Conn, ln net.Listener, log logger.Logger) error {
|
||||
// Upgrade connection to multiplex stream.
|
||||
session, err := mux.ClientSession(conn)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
go func() {
|
||||
defer ln.Close()
|
||||
for {
|
||||
conn, err := session.Accept()
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
conn.Close() // we do not handle incoming connections.
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
rc, err := ln.Accept()
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
log.Debugf("peer %s accepted", rc.RemoteAddr())
|
||||
|
||||
go func(c net.Conn) {
|
||||
defer c.Close()
|
||||
|
||||
log = log.WithFields(map[string]any{
|
||||
"local": ln.Addr().String(),
|
||||
"remote": c.RemoteAddr().String(),
|
||||
})
|
||||
|
||||
sc, err := session.GetConn()
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
defer sc.Close()
|
||||
|
||||
af := &relay.AddrFeature{}
|
||||
af.ParseFrom(c.RemoteAddr().String())
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
Features: []relay.Feature{af},
|
||||
}
|
||||
if _, err := resp.WriteTo(sc); err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
t := time.Now()
|
||||
log.Infof("%s <-> %s", c.LocalAddr(), c.RemoteAddr())
|
||||
netpkg.Transport(sc, c)
|
||||
log.WithFields(map[string]any{"duration": time.Since(t)}).
|
||||
Infof("%s >-< %s", c.LocalAddr(), c.RemoteAddr())
|
||||
}(rc)
|
||||
}
|
||||
}
|
81
handler/relay/conn.go
Normal file
81
handler/relay/conn.go
Normal file
@ -0,0 +1,81 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
)
|
||||
|
||||
type tcpConn struct {
|
||||
net.Conn
|
||||
wbuf bytes.Buffer
|
||||
}
|
||||
|
||||
func (c *tcpConn) Read(b []byte) (n int, err error) {
|
||||
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.wbuf.WriteTo(c.Conn)
|
||||
return
|
||||
}
|
||||
_, err = c.Conn.Write(b)
|
||||
return
|
||||
}
|
||||
|
||||
type udpConn struct {
|
||||
net.Conn
|
||||
wbuf bytes.Buffer
|
||||
}
|
||||
|
||||
func (c *udpConn) Read(b []byte) (n int, err error) {
|
||||
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 := make([]byte, dlen)
|
||||
_, 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)
|
||||
}
|
91
handler/relay/connect.go
Normal file
91
handler/relay/connect.go
Normal file
@ -0,0 +1,91 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
netpkg "github.com/go-gost/gost/v3/pkg/common/net"
|
||||
"github.com/go-gost/gost/v3/pkg/logger"
|
||||
"github.com/go-gost/relay"
|
||||
)
|
||||
|
||||
func (h *relayHandler) handleConnect(ctx context.Context, conn net.Conn, network, address string, log logger.Logger) error {
|
||||
log = log.WithFields(map[string]any{
|
||||
"dst": fmt.Sprintf("%s/%s", address, network),
|
||||
"cmd": "connect",
|
||||
})
|
||||
|
||||
log.Infof("%s >> %s", conn.RemoteAddr(), address)
|
||||
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
}
|
||||
|
||||
if address == "" {
|
||||
resp.Status = relay.StatusBadRequest
|
||||
resp.WriteTo(conn)
|
||||
err := errors.New("target not specified")
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
if h.options.Bypass != nil && h.options.Bypass.Contains(address) {
|
||||
log.Info("bypass: ", address)
|
||||
resp.Status = relay.StatusForbidden
|
||||
_, err := resp.WriteTo(conn)
|
||||
return err
|
||||
}
|
||||
|
||||
cc, err := h.router.Dial(ctx, network, address)
|
||||
if err != nil {
|
||||
resp.Status = relay.StatusNetworkUnreachable
|
||||
resp.WriteTo(conn)
|
||||
return err
|
||||
}
|
||||
defer cc.Close()
|
||||
|
||||
if h.md.noDelay {
|
||||
if _, err := resp.WriteTo(conn); err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
switch network {
|
||||
case "udp", "udp4", "udp6":
|
||||
rc := &udpConn{
|
||||
Conn: conn,
|
||||
}
|
||||
if !h.md.noDelay {
|
||||
// cache the header
|
||||
if _, err := resp.WriteTo(&rc.wbuf); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
conn = rc
|
||||
default:
|
||||
rc := &tcpConn{
|
||||
Conn: conn,
|
||||
}
|
||||
if !h.md.noDelay {
|
||||
// cache the header
|
||||
if _, err := resp.WriteTo(&rc.wbuf); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
conn = rc
|
||||
}
|
||||
|
||||
t := time.Now()
|
||||
log.Infof("%s <-> %s", conn.RemoteAddr(), address)
|
||||
netpkg.Transport(conn, cc)
|
||||
log.WithFields(map[string]any{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.RemoteAddr(), address)
|
||||
|
||||
return nil
|
||||
}
|
91
handler/relay/forward.go
Normal file
91
handler/relay/forward.go
Normal file
@ -0,0 +1,91 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
netpkg "github.com/go-gost/gost/v3/pkg/common/net"
|
||||
"github.com/go-gost/gost/v3/pkg/logger"
|
||||
"github.com/go-gost/relay"
|
||||
)
|
||||
|
||||
func (h *relayHandler) handleForward(ctx context.Context, conn net.Conn, network string, log logger.Logger) error {
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
}
|
||||
target := h.group.Next()
|
||||
if target == nil {
|
||||
resp.Status = relay.StatusServiceUnavailable
|
||||
resp.WriteTo(conn)
|
||||
err := errors.New("target not available")
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
log = log.WithFields(map[string]any{
|
||||
"dst": fmt.Sprintf("%s/%s", target.Addr, network),
|
||||
"cmd": "forward",
|
||||
})
|
||||
|
||||
log.Infof("%s >> %s", conn.RemoteAddr(), target.Addr)
|
||||
|
||||
cc, err := h.router.Dial(ctx, network, target.Addr)
|
||||
if err != nil {
|
||||
// TODO: the router itself may be failed due to the failed node in the router,
|
||||
// the dead marker may be a wrong operation.
|
||||
target.Marker.Mark()
|
||||
|
||||
resp.Status = relay.StatusHostUnreachable
|
||||
resp.WriteTo(conn)
|
||||
log.Error(err)
|
||||
|
||||
return err
|
||||
}
|
||||
defer cc.Close()
|
||||
target.Marker.Reset()
|
||||
|
||||
if h.md.noDelay {
|
||||
if _, err := resp.WriteTo(conn); err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
switch network {
|
||||
case "udp", "udp4", "udp6":
|
||||
rc := &udpConn{
|
||||
Conn: conn,
|
||||
}
|
||||
if !h.md.noDelay {
|
||||
// cache the header
|
||||
if _, err := resp.WriteTo(&rc.wbuf); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
conn = rc
|
||||
default:
|
||||
rc := &tcpConn{
|
||||
Conn: conn,
|
||||
}
|
||||
if !h.md.noDelay {
|
||||
// cache the header
|
||||
if _, err := resp.WriteTo(&rc.wbuf); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
conn = rc
|
||||
}
|
||||
|
||||
t := time.Now()
|
||||
log.Infof("%s <-> %s", conn.RemoteAddr(), target.Addr)
|
||||
netpkg.Transport(conn, cc)
|
||||
log.WithFields(map[string]any{
|
||||
"duration": time.Since(t),
|
||||
}).Infof("%s >-< %s", conn.RemoteAddr(), target.Addr)
|
||||
|
||||
return nil
|
||||
}
|
147
handler/relay/handler.go
Normal file
147
handler/relay/handler.go
Normal file
@ -0,0 +1,147 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-gost/gost/v3/pkg/chain"
|
||||
"github.com/go-gost/gost/v3/pkg/handler"
|
||||
md "github.com/go-gost/gost/v3/pkg/metadata"
|
||||
"github.com/go-gost/gost/v3/pkg/registry"
|
||||
"github.com/go-gost/relay"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrBadVersion = errors.New("relay: bad version")
|
||||
ErrUnknownCmd = errors.New("relay: unknown command")
|
||||
)
|
||||
|
||||
func init() {
|
||||
registry.HandlerRegistry().Register("relay", NewHandler)
|
||||
}
|
||||
|
||||
type relayHandler struct {
|
||||
group *chain.NodeGroup
|
||||
router *chain.Router
|
||||
md metadata
|
||||
options handler.Options
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.Options{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
return &relayHandler{
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *relayHandler) Init(md md.Metadata) (err error) {
|
||||
if err := h.parseMetadata(md); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
h.router = h.options.Router
|
||||
if h.router == nil {
|
||||
h.router = (&chain.Router{}).WithLogger(h.options.Logger)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Forward implements handler.Forwarder.
|
||||
func (h *relayHandler) Forward(group *chain.NodeGroup) {
|
||||
h.group = group
|
||||
}
|
||||
|
||||
func (h *relayHandler) Handle(ctx context.Context, conn net.Conn, opts ...handler.HandleOption) error {
|
||||
defer conn.Close()
|
||||
|
||||
start := time.Now()
|
||||
log := h.options.Logger.WithFields(map[string]any{
|
||||
"remote": conn.RemoteAddr().String(),
|
||||
"local": conn.LocalAddr().String(),
|
||||
})
|
||||
|
||||
log.Infof("%s <> %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
defer func() {
|
||||
log.WithFields(map[string]any{
|
||||
"duration": time.Since(start),
|
||||
}).Infof("%s >< %s", conn.RemoteAddr(), conn.LocalAddr())
|
||||
}()
|
||||
|
||||
if h.md.readTimeout > 0 {
|
||||
conn.SetReadDeadline(time.Now().Add(h.md.readTimeout))
|
||||
}
|
||||
|
||||
req := relay.Request{}
|
||||
if _, err := req.ReadFrom(conn); err != nil {
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
|
||||
if req.Version != relay.Version1 {
|
||||
err := ErrBadVersion
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
var user, pass string
|
||||
var address string
|
||||
for _, f := range req.Features {
|
||||
if f.Type() == relay.FeatureUserAuth {
|
||||
feature := f.(*relay.UserAuthFeature)
|
||||
user, pass = feature.Username, feature.Password
|
||||
}
|
||||
if f.Type() == relay.FeatureAddr {
|
||||
feature := f.(*relay.AddrFeature)
|
||||
address = net.JoinHostPort(feature.Host, strconv.Itoa(int(feature.Port)))
|
||||
}
|
||||
}
|
||||
|
||||
if user != "" {
|
||||
log = log.WithFields(map[string]any{"user": user})
|
||||
}
|
||||
|
||||
resp := relay.Response{
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
}
|
||||
if h.options.Auther != nil && !h.options.Auther.Authenticate(user, pass) {
|
||||
resp.Status = relay.StatusUnauthorized
|
||||
log.Error("unauthorized")
|
||||
_, err := resp.WriteTo(conn)
|
||||
return err
|
||||
}
|
||||
|
||||
network := "tcp"
|
||||
if (req.Flags & relay.FUDP) == relay.FUDP {
|
||||
network = "udp"
|
||||
}
|
||||
|
||||
if h.group != nil {
|
||||
if address != "" {
|
||||
resp.Status = relay.StatusForbidden
|
||||
log.Error("forward mode, connect is forbidden")
|
||||
_, err := resp.WriteTo(conn)
|
||||
return err
|
||||
}
|
||||
// forward mode
|
||||
return h.handleForward(ctx, conn, network, log)
|
||||
}
|
||||
|
||||
switch req.Flags & relay.CmdMask {
|
||||
case 0, relay.CONNECT:
|
||||
return h.handleConnect(ctx, conn, network, address, log)
|
||||
case relay.BIND:
|
||||
return h.handleBind(ctx, conn, network, address, log)
|
||||
}
|
||||
return ErrUnknownCmd
|
||||
}
|
35
handler/relay/metadata.go
Normal file
35
handler/relay/metadata.go
Normal file
@ -0,0 +1,35 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
mdata "github.com/go-gost/gost/v3/pkg/metadata"
|
||||
)
|
||||
|
||||
type metadata struct {
|
||||
readTimeout time.Duration
|
||||
enableBind bool
|
||||
udpBufferSize int
|
||||
noDelay bool
|
||||
}
|
||||
|
||||
func (h *relayHandler) parseMetadata(md mdata.Metadata) (err error) {
|
||||
const (
|
||||
readTimeout = "readTimeout"
|
||||
enableBind = "bind"
|
||||
udpBufferSize = "udpBufferSize"
|
||||
noDelay = "nodelay"
|
||||
)
|
||||
|
||||
h.md.readTimeout = mdata.GetDuration(md, readTimeout)
|
||||
h.md.enableBind = mdata.GetBool(md, enableBind)
|
||||
h.md.noDelay = mdata.GetBool(md, noDelay)
|
||||
|
||||
if bs := mdata.GetInt(md, udpBufferSize); bs > 0 {
|
||||
h.md.udpBufferSize = int(math.Min(math.Max(float64(bs), 512), 64*1024))
|
||||
} else {
|
||||
h.md.udpBufferSize = 1024
|
||||
}
|
||||
return
|
||||
}
|
Reference in New Issue
Block a user