Files
Leonov Vladislav 1c42c638a6 recorder: emit periodic session snapshots and byte deltas
Handlers write one recorder entry when a session ends, so long-lived
SOCKS5 tunnels, streaming HTTP responses and UDP associations stay
invisible while they run and report their traffic as one late record.

With recorder.period set, a session now emits interim records on the
interval while it is active and one final record when it ends. Each
record carries the cumulative counters alongside the increments since the
previous one, so a consumer sums records instead of replacing them, plus
sessionID, recordIndex and phase. A session that ends inside one period
still writes a single record, as it does today.

One goroutine per handler samples every live session on the tick and
writes its record straight to the recorder. There is no queue and no
retry loop, and none is needed: a session moves its cursor past a record
only once the recorder has taken it, so a refused write costs no bytes.
They stay in the delta and go out with the next record. Holding on to
what the sink cannot take right now is the sink's job.

Interim and Finish take a context and return an error, so a handler
learns what became of every record it asked for. Start writes nothing, so
it takes neither. Close stops the sampling and reports the sessions its
owner had not finished; nothing is buffered, so there is nothing to
drain.

With recorder.period unset or non-positive the previous behaviour is
kept: one record per session, written inline, in the old shape. An object
its handler never stamped, and one whose record mode is off, is dropped
in both modes.
2026-09-15 15:05:02 +03:00

191 lines
4.5 KiB
Go

package v5
import (
"context"
"net"
"time"
"github.com/go-gost/core/limiter"
"github.com/go-gost/core/logger"
"github.com/go-gost/core/observer/stats"
"github.com/go-gost/gosocks5"
xctx "github.com/go-gost/x/ctx"
ictx "github.com/go-gost/x/internal/ctx"
xnet "github.com/go-gost/x/internal/net"
traffic_wrapper "github.com/go-gost/x/limiter/traffic/wrapper"
stats_wrapper "github.com/go-gost/x/observer/stats/wrapper"
xrecorder "github.com/go-gost/x/recorder"
)
func (h *socks5Handler) handleBind(ctx context.Context, conn net.Conn, network, address string, ro *xrecorder.HandlerRecorderObject, log logger.Logger) error {
log = log.WithFields(map[string]any{
"dst": address,
"cmd": "bind",
})
log.Debugf("%s >> %s", conn.RemoteAddr(), address)
if !h.md.enableBind {
reply := gosocks5.NewReply(gosocks5.NotAllowed, nil)
log.Trace(reply)
log.Error("socks5: BIND is disabled")
return reply.Write(conn)
}
{
clientID := xctx.ClientIDFromContext(ctx)
rw := traffic_wrapper.WrapReadWriter(
h.limiter,
conn,
string(clientID),
limiter.ServiceOption(h.options.Service),
limiter.ScopeOption(limiter.ScopeClient),
limiter.NetworkOption(network),
limiter.AddrOption(address),
limiter.ClientOption(string(clientID)),
limiter.SrcOption(conn.RemoteAddr().String()),
)
if h.options.Observer != nil {
pstats := h.stats.Stats(string(clientID))
pstats.Add(stats.KindTotalConns, 1)
pstats.Add(stats.KindCurrentConns, 1)
defer pstats.Add(stats.KindCurrentConns, -1)
rw = stats_wrapper.WrapReadWriter(rw, pstats)
}
conn = xnet.NewReadWriteConn(rw, rw, conn)
}
// BIND does not support chain.
return h.bindLocal(ctx, conn, network, address, ro, log)
}
func (h *socks5Handler) bindLocal(ctx context.Context, conn net.Conn, network, address string, ro *xrecorder.HandlerRecorderObject, log logger.Logger) error {
lc := xnet.ListenConfig{
Netns: h.options.Netns,
}
ln, err := lc.Listen(ctx, network, address) // strict mode: if the port already in use, it will return error
if err != nil {
log.Error(err)
reply := gosocks5.NewReply(gosocks5.Failure, nil)
if err := reply.Write(conn); err != nil {
log.Error(err)
}
log.Debug(reply)
return err
}
log = log.WithFields(map[string]any{
"src": ln.Addr().String(),
"bind": ln.Addr().String(),
})
ro.SrcAddr = ln.Addr().String()
ictx.SessionFromContext(ctx).Start(*ro)
socksAddr := gosocks5.Addr{}
if err := socksAddr.ParseFrom(ln.Addr().String()); err != nil {
log.Warn(err)
}
// Issue: may not reachable when host has multi-interface
socksAddr.Host, _, _ = net.SplitHostPort(conn.LocalAddr().String())
if h.md.publicAddr != "" {
socksAddr.Host = h.md.publicAddr
}
socksAddr.Type = 0
reply := gosocks5.NewReply(gosocks5.Succeeded, &socksAddr)
log.Trace(reply)
if err := reply.Write(conn); err != nil {
log.Error(err)
ln.Close()
return err
}
log.Debugf("bind on %s OK", ln.Addr())
h.serveBind(ctx, conn, ln, log)
return nil
}
func (h *socks5Handler) serveBind(ctx context.Context, conn net.Conn, ln net.Listener, log logger.Logger) {
var rc net.Conn
accept := func() <-chan error {
errc := make(chan error, 1)
go func() {
defer close(errc)
defer ln.Close()
c, err := ln.Accept()
if err != nil {
errc <- err
}
rc = c
}()
return errc
}
pc1, pc2 := net.Pipe()
pipe := func() <-chan error {
errc := make(chan error, 1)
go func() {
defer close(errc)
defer pc1.Close()
// errc <- xnet.Transport(conn, pc1)
errc <- xnet.Pipe(ctx, conn, pc1)
}()
return errc
}
defer pc2.Close()
select {
case err := <-accept():
if err != nil {
log.Error(err)
reply := gosocks5.NewReply(gosocks5.Failure, nil)
log.Trace(reply)
if err := reply.Write(pc2); err != nil {
log.Error(err)
}
return
}
defer rc.Close()
log.Debugf("peer %s accepted", rc.RemoteAddr())
log = log.WithFields(map[string]any{
"local": rc.LocalAddr().String(),
"remote": rc.RemoteAddr().String(),
})
raddr := gosocks5.Addr{}
raddr.ParseFrom(rc.RemoteAddr().String())
reply := gosocks5.NewReply(gosocks5.Succeeded, &raddr)
log.Trace(reply)
if err := reply.Write(pc2); err != nil {
log.Error(err)
}
start := time.Now()
log.Debugf("%s <-> %s", rc.LocalAddr(), rc.RemoteAddr())
// xnet.Transport(pc2, rc)
xnet.Pipe(ctx, pc2, rc)
log.WithFields(map[string]any{"duration": time.Since(start)}).
Debugf("%s >-< %s", rc.LocalAddr(), rc.RemoteAddr())
case err := <-pipe():
if err != nil {
log.Error(err)
}
ln.Close()
return
}
}