fix: утечки, уровни logx, обход логгера
- logx: добавить префиксы [DEBUG]/[INFO]/[WARN]/[ERROR]; уровни были
неразличимы в выводе (всё шло через голый log.Printf).
- logx: добавить хелпер OrNop для nil-проверок на стороне конструктора.
- vkauth/{client,token}.go: заменить прямой log.Printf на c.log.Infof
(97 мест обходили унифицированный логгер после прошлого рефакторинга).
- udprelay.oneTURN: буферизовать error chan (cap 1) + select на ctx.Done в
TURNLoop — небуферизованный send блокировался навсегда, когда TURNLoop
выходил по ctx до чтения, утекали горутина + TURN-стрим.
- udprelay: перенести write-цикл conn2->relay в wg.Go (был голый go func, мог
пережить wg.Wait и читать из закрытого conn).
- udprelay.TURNLoop: заменить time.Sleep(2s) на select+ctx, чтобы shutdown не
блокировался per-stream.
- udprelay.Run / tcpfwd.Run: возвращать error вместо log.Panicf при сбое listen;
cmd/* теперь log.Fatalf на всплывшей ошибке.
- cmd/*: log.Panicf → log.Fatalf для CLI-ошибок (без stack trace на плохой флаг).
- kcptun.NewKCPOverDTLS: закрывать серверный kcp.Listener на error-путях после
SetDeadline/AcceptKCP (утекал при любом сбое).
- doc пакета udprelay: переписать устаревшее утверждение "avoid importing
vkauth" (файл импортирует vkauth ради sentinel-ошибок).
- udprelay: lifecycle-сообщения ("Established/Closed DTLS connection")
Errorf → Infof; строка "relayed-address" под DebugEnabled использует Debugf.
- tcpfwd: lifecycle-сообщения ("connected/disconnected/waiting/listening")
Errorf → Infof, "failed to wrap listener" → Warnf.
- tcpfwd.maintainSession doc: "fixed 2-3s backoff" было неверно (3s при сбое
setup, 2s после disconnect).
- pool.go doc: "bond client (in main)" → internal/proxy/bondclient.
- srtpmimicry.Unwrap: doc предупреждает, что AEAD открывает in-place внутри
wire, поэтому вызыватели должны считать wire потреблённым.
- комментарии-алиасы GetCredsFunc udprelay/tcpfwd: убрать фикцию "cmd/main
wiring stability" (всё в internal/).
Build чисто, go vet чисто, все тесты проходят.
This commit is contained in:
1 parent
aff95e87d3
commit
52e7cb83e6
11 files changed
+96
-177
No files matched your search
@@ -56,7 +56,7 @@ func main() {
|
||||
|
||||
cfg, err := config.ParseClient(os.Args[1:], os.Stderr)
|
||||
if err != nil {
|
||||
log.Panicf("%v", err)
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
if cfg.DNS.Servers != nil {
|
||||
@@ -111,7 +111,9 @@ func main() {
|
||||
WrapKey: cfg.Obf.WrapKey,
|
||||
GetCreds: tcpfwd.GetCredsFunc(vkAuth.GetCredentials),
|
||||
}
|
||||
tcpfwd.Run(ctx, vlessDeps, vlessParams, peer, cfg.Proxy.Listen, cfg.TURN.N, cfg.Proxy.Mode == config.ProxyModeTCPFwdBond)
|
||||
if err := tcpfwd.Run(ctx, vlessDeps, vlessParams, peer, cfg.Proxy.Listen, cfg.TURN.N, cfg.Proxy.Mode == config.ProxyModeTCPFwdBond); err != nil {
|
||||
log.Fatalf("tcpfwd: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -127,5 +129,7 @@ func main() {
|
||||
WrapKey: cfg.Obf.WrapKey,
|
||||
GetCreds: udprelay.GetCredsFunc(vkAuth.GetCredentials),
|
||||
}
|
||||
udprelay.Run(ctx, udpDtlsDialer, vkAuth, logger, &connectedStreams, cancel, udpParams, peer, cfg.Proxy.Listen, cfg.TURN.N)
|
||||
if err := udprelay.Run(ctx, udpDtlsDialer, vkAuth, logger, &connectedStreams, cancel, udpParams, peer, cfg.Proxy.Listen, cfg.TURN.N); err != nil {
|
||||
log.Fatalf("udprelay: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
func main() {
|
||||
cfg, err := config.ParseServer(os.Args[1:], os.Stderr)
|
||||
if err != nil {
|
||||
log.Panicf("%v", err)
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
logger := logx.New(cfg.Log.Debug)
|
||||
registry := bondserver.NewRegistry(bondserver.Deps{Log: logger})
|
||||
@@ -32,7 +32,7 @@ func main() {
|
||||
if cfg.Obf.GenWrapKey {
|
||||
key, gerr := srtpmimicry.GenKeyHex()
|
||||
if gerr != nil {
|
||||
log.Panicf("gen-wrap-key: %v", gerr)
|
||||
log.Fatalf("gen-wrap-key: %v", gerr)
|
||||
}
|
||||
fmt.Println(key)
|
||||
return
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"strings"
|
||||
@@ -157,12 +156,12 @@ func (c *Client) HandleAuthError(streamID int) bool {
|
||||
count := cache.errorCount.Add(1)
|
||||
cache.lastErrorTime.Store(now)
|
||||
|
||||
log.Printf("[STREAM %d] Auth error (cache=%d, count=%d/%d)", streamID, cacheID, count, MaxCacheErrors)
|
||||
c.log.Infof("[STREAM %d] Auth error (cache=%d, count=%d/%d)", streamID, cacheID, count, MaxCacheErrors)
|
||||
|
||||
if count >= MaxCacheErrors {
|
||||
log.Printf("[VK Auth] Multiple auth errors detected (%d), invalidating cache %d for stream %d...", count, cacheID, streamID)
|
||||
c.log.Infof("[VK Auth] Multiple auth errors detected (%d), invalidating cache %d for stream %d...", count, cacheID, streamID)
|
||||
cache.Invalidate()
|
||||
log.Printf("[STREAM %d] [VK Auth] Credentials cache invalidated", streamID)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Credentials cache invalidated", streamID)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -198,7 +197,7 @@ func (c *Client) fetchSerialized(ctx context.Context, link string, streamID int)
|
||||
elapsed := time.Since(c.lastFetchTime)
|
||||
if !c.lastFetchTime.IsZero() && elapsed < minInterval {
|
||||
wait := minInterval - elapsed
|
||||
log.Printf("[STREAM %d] [VK Auth] Throttling: waiting %v to prevent rate limit...", streamID, wait.Truncate(time.Millisecond))
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Throttling: waiting %v to prevent rate limit...", streamID, wait.Truncate(time.Millisecond))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", "", nil, ctx.Err()
|
||||
@@ -218,22 +217,22 @@ func (c *Client) fetch(ctx context.Context, link string, streamID int) (string,
|
||||
var lastErr error
|
||||
jar := tlsclient.NewCookieJar()
|
||||
for _, creds := range c.credentials {
|
||||
log.Printf("[STREAM %d] [VK Auth] Trying credentials: client_id=%s", streamID, creds.ClientID)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Trying credentials: client_id=%s", streamID, creds.ClientID)
|
||||
|
||||
user, pass, addrs, err := c.tokenChain(ctx, link, streamID, creds, jar)
|
||||
if err == nil {
|
||||
log.Printf("[STREAM %d] [VK Auth] Success with client_id=%s", streamID, creds.ClientID)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Success with client_id=%s", streamID, creds.ClientID)
|
||||
return user, pass, addrs, nil
|
||||
}
|
||||
lastErr = err
|
||||
log.Printf("[STREAM %d] [VK Auth] Failed with client_id=%s: %v", streamID, creds.ClientID, err)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Failed with client_id=%s: %v", streamID, creds.ClientID, err)
|
||||
|
||||
if errors.Is(err, ErrCaptchaWaitRequired) || errors.Is(err, ErrFatalCaptchaNoStreams) {
|
||||
return "", "", nil, err
|
||||
}
|
||||
es := err.Error()
|
||||
if strings.Contains(es, "error_code:29") || strings.Contains(es, "error_code: 29") || strings.Contains(es, "Rate limit") {
|
||||
log.Printf("[STREAM %d] [VK Auth] Rate limit detected, trying next credentials...", streamID)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Rate limit detected, trying next credentials...", streamID)
|
||||
}
|
||||
}
|
||||
return "", "", nil, fmt.Errorf("all VK credentials failed: %w", lastErr)
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
neturl "net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -46,7 +45,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
name := namegen.Generate()
|
||||
escapedName := neturl.QueryEscape(name)
|
||||
|
||||
log.Printf("[STREAM %d] [VK Auth] Connecting Identity - Name: %s | User-Agent: %s", streamID, name, profile.UserAgent)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Connecting Identity - Name: %s | User-Agent: %s", streamID, name, profile.UserAgent)
|
||||
|
||||
doRequest := func(data string, url string) (resp map[string]any, err error) {
|
||||
parsedURL, err := neturl.Parse(url)
|
||||
@@ -76,7 +75,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := httpResp.Body.Close(); closeErr != nil {
|
||||
log.Printf("close response body: %s", closeErr)
|
||||
c.log.Infof("close response body: %s", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -110,7 +109,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
// Token 1 -> getCallPreview (warmup, non-fatal).
|
||||
data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&fields=photo_200&access_token=%s", link, token1)
|
||||
if _, prevErr := doRequest(data, "https://api.vk.ru/method/calls.getCallPreview?v=5.275&client_id="+creds.ClientID); prevErr != nil {
|
||||
log.Printf("[STREAM %d] [VK Auth] Warning: getCallPreview failed: %v", streamID, prevErr)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Warning: getCallPreview failed: %v", streamID, prevErr)
|
||||
}
|
||||
|
||||
vkDelayRandom(200, 400)
|
||||
@@ -131,10 +130,10 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
if captchaErr != nil && captchaErr.IsCaptcha() {
|
||||
solveMode, hasSolveMode := CaptchaSolveModeForAttempt(attempt, c.manualOnly)
|
||||
if !hasSolveMode {
|
||||
log.Printf("[STREAM %d] [Captcha] No more solve modes available (attempt %d)", streamID, attempt+1)
|
||||
c.log.Infof("[STREAM %d] [Captcha] No more solve modes available (attempt %d)", streamID, attempt+1)
|
||||
c.engageLockout(60 * time.Second)
|
||||
if c.streamsFn() == 0 {
|
||||
log.Printf("[STREAM %d] [FATAL] 0 connected streams and captcha solve modes exhausted.", streamID)
|
||||
c.log.Infof("[STREAM %d] [FATAL] 0 connected streams and captcha solve modes exhausted.", streamID)
|
||||
return "", "", nil, ErrFatalCaptchaNoStreams
|
||||
}
|
||||
return "", "", nil, ErrCaptchaWaitRequired
|
||||
@@ -153,7 +152,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
if captchaErr.SessionToken != "" && captchaErr.RedirectURI != "" {
|
||||
successToken, solveErr = solveFn(ctx, captchaErr, streamID, client, profile)
|
||||
if solveErr != nil {
|
||||
log.Printf("[STREAM %d] [Captcha] Auto captcha failed: %v", streamID, solveErr)
|
||||
c.log.Infof("[STREAM %d] [Captcha] Auto captcha failed: %v", streamID, solveErr)
|
||||
}
|
||||
} else {
|
||||
solveErr = fmt.Errorf("missing fields for auto solve")
|
||||
@@ -163,7 +162,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
solveErr = fmt.Errorf("manual captcha solver not configured")
|
||||
break
|
||||
}
|
||||
log.Printf("[STREAM %d] [Captcha] Triggering manual captcha fallback...", streamID)
|
||||
c.log.Infof("[STREAM %d] [Captcha] Triggering manual captcha fallback...", streamID)
|
||||
// Manual solver gets its own 3-min budget so a tight parent
|
||||
// deadline doesn't cut user solve time. We still propagate
|
||||
// parent cancellation (app shutdown) so the in-flight solver
|
||||
@@ -188,12 +187,12 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
solveErr = res.err
|
||||
if successToken != "" || captchaKey != "" {
|
||||
if solveErr != nil {
|
||||
log.Printf("[STREAM %d] [Captcha] Token received (ignoring cleanup error: %v)", streamID, solveErr)
|
||||
c.log.Infof("[STREAM %d] [Captcha] Token received (ignoring cleanup error: %v)", streamID, solveErr)
|
||||
solveErr = nil
|
||||
}
|
||||
log.Printf("[STREAM %d] [Captcha] Successfully got token from browser", streamID)
|
||||
c.log.Infof("[STREAM %d] [Captcha] Successfully got token from browser", streamID)
|
||||
} else if solveErr != nil {
|
||||
log.Printf("[STREAM %d] [Captcha] manual solver returned error: %v", streamID, solveErr)
|
||||
c.log.Infof("[STREAM %d] [Captcha] manual solver returned error: %v", streamID, solveErr)
|
||||
}
|
||||
case <-manualCtx.Done():
|
||||
if errors.Is(manualCtx.Err(), context.DeadlineExceeded) {
|
||||
@@ -206,15 +205,15 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
}
|
||||
|
||||
if solveErr != nil {
|
||||
log.Printf("[STREAM %d] [Captcha] %s failed (attempt %d): %v", streamID, CaptchaSolveModeLabel(solveMode), attempt+1, solveErr)
|
||||
c.log.Infof("[STREAM %d] [Captcha] %s failed (attempt %d): %v", streamID, CaptchaSolveModeLabel(solveMode), attempt+1, solveErr)
|
||||
nextSolveMode, hasNextSolveMode := CaptchaSolveModeForAttempt(attempt+1, c.manualOnly)
|
||||
if hasNextSolveMode {
|
||||
log.Printf("[STREAM %d] [Captcha] Falling back to %s...", streamID, CaptchaSolveModeLabel(nextSolveMode))
|
||||
c.log.Infof("[STREAM %d] [Captcha] Falling back to %s...", streamID, CaptchaSolveModeLabel(nextSolveMode))
|
||||
continue
|
||||
}
|
||||
c.engageLockout(60 * time.Second)
|
||||
if c.streamsFn() == 0 {
|
||||
log.Printf("[STREAM %d] [FATAL] 0 connected streams and manual captcha failed/timed out.", streamID)
|
||||
c.log.Infof("[STREAM %d] [FATAL] 0 connected streams and manual captcha failed/timed out.", streamID)
|
||||
return "", "", nil, ErrFatalCaptchaNoStreams
|
||||
}
|
||||
return "", "", nil, ErrCaptchaWaitRequired
|
||||
@@ -285,9 +284,9 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
return "", "", nil, fmt.Errorf("missing or empty urls in turn_server")
|
||||
}
|
||||
|
||||
log.Printf("[STREAM %d] [VK Auth] TURN urls (%d total):", streamID, len(urlsRaw))
|
||||
c.log.Infof("[STREAM %d] [VK Auth] TURN urls (%d total):", streamID, len(urlsRaw))
|
||||
for i, u := range urlsRaw {
|
||||
log.Printf("[STREAM %d] [VK Auth] [%d] %v", streamID, i, u)
|
||||
c.log.Infof("[STREAM %d] [VK Auth] [%d] %v", streamID, i, u)
|
||||
}
|
||||
|
||||
var addresses []string
|
||||
|
||||
+13
-4
@@ -33,14 +33,23 @@ func Nop() Logger { return nopLogger{} }
|
||||
|
||||
func (l *stdLogger) Debugf(format string, v ...any) {
|
||||
if l.debug {
|
||||
log.Printf(format, v...)
|
||||
log.Printf("[DEBUG] "+format, v...)
|
||||
}
|
||||
}
|
||||
func (l *stdLogger) Infof(format string, v ...any) { log.Printf(format, v...) }
|
||||
func (l *stdLogger) Warnf(format string, v ...any) { log.Printf(format, v...) }
|
||||
func (l *stdLogger) Errorf(format string, v ...any) { log.Printf(format, v...) }
|
||||
func (l *stdLogger) Infof(format string, v ...any) { log.Printf("[INFO] "+format, v...) }
|
||||
func (l *stdLogger) Warnf(format string, v ...any) { log.Printf("[WARN] "+format, v...) }
|
||||
func (l *stdLogger) Errorf(format string, v ...any) { log.Printf("[ERROR] "+format, v...) }
|
||||
func (l *stdLogger) DebugEnabled() bool { return l.debug }
|
||||
|
||||
// OrNop returns l if non-nil, else a Nop logger. Use in package constructors
|
||||
// that accept a nullable Logger.
|
||||
func OrNop(l Logger) Logger {
|
||||
if l == nil {
|
||||
return Nop()
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
type nopLogger struct{}
|
||||
|
||||
func (nopLogger) Debugf(string, ...any) {}
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
)
|
||||
|
||||
// PooledSession is a single TURN+DTLS+KCP+smux session inside the pool, with
|
||||
// its lifetime counters. Fields are exported so the bond client (in main) can
|
||||
// account per-lane traffic; mutate via the atomic operations only.
|
||||
// its lifetime counters. Fields are exported so internal/proxy/bondclient can
|
||||
// account per-lane traffic; mutate the atomics via their atomic methods only.
|
||||
type PooledSession struct {
|
||||
ID int
|
||||
Sess *smux.Session
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,8 +18,8 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// GetCredsFunc is an alias of common.GetCredsFunc kept for cmd/main wiring
|
||||
// stability.
|
||||
// GetCredsFunc is re-exported from common so callers can keep their imports
|
||||
// scoped to this package.
|
||||
type GetCredsFunc = common.GetCredsFunc
|
||||
|
||||
// Params is the per-pool TURN/wrap configuration.
|
||||
@@ -55,7 +54,7 @@ func (d *Deps) log() logx.Logger {
|
||||
// Run is the VLESS-mode entrypoint. It spawns numSessions maintainers, waits
|
||||
// for at least one to connect, then accepts local TCP connections and forwards
|
||||
// each as a smux stream (round-robin) or bonded across all live sessions.
|
||||
func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) {
|
||||
func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) error {
|
||||
pool := &SessionPool{}
|
||||
|
||||
var wgMaint sync.WaitGroup
|
||||
@@ -70,12 +69,12 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
})
|
||||
}
|
||||
|
||||
deps.log().Errorf("VLESS mode: waiting for sessions to connect (total: %d)...", numSessions)
|
||||
deps.log().Infof("VLESS mode: waiting for sessions to connect (total: %d)...", numSessions)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
wgMaint.Wait()
|
||||
return
|
||||
return nil
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
if pool.Count() > 0 {
|
||||
@@ -85,20 +84,21 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
|
||||
listener, err := net.Listen("tcp", listenAddr)
|
||||
if err != nil {
|
||||
log.Panicf("TCP listen: %s", err)
|
||||
wgMaint.Wait()
|
||||
return fmt.Errorf("tcpfwd listen %s: %w", listenAddr, err)
|
||||
}
|
||||
|
||||
wrappedListener, err := ish.WrapListener(listener)
|
||||
if err != nil {
|
||||
deps.log().Errorf("Warning: failed to wrap listener: %v", err)
|
||||
deps.log().Warnf("failed to wrap listener: %v", err)
|
||||
wrappedListener = listener
|
||||
}
|
||||
|
||||
context.AfterFunc(ctx, func() { _ = wrappedListener.Close() })
|
||||
if useBond {
|
||||
deps.log().Errorf("VLESS bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr)
|
||||
deps.log().Infof("VLESS bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr)
|
||||
} else {
|
||||
deps.log().Errorf("VLESS mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
||||
deps.log().Infof("VLESS mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
||||
}
|
||||
|
||||
var wgConn sync.WaitGroup
|
||||
@@ -109,7 +109,7 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
case <-ctx.Done():
|
||||
wgConn.Wait()
|
||||
wgMaint.Wait()
|
||||
return
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
deps.log().Errorf("TCP accept error: %s", err)
|
||||
@@ -176,8 +176,9 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
}
|
||||
}
|
||||
|
||||
// maintainSession keeps one TURN+DTLS+KCP+smux session alive, reconnecting on
|
||||
// failure with a fixed 2-3s backoff.
|
||||
// maintainSession keeps one TURN+DTLS+KCP+smux session alive: 3s backoff on
|
||||
// setup failure, 2s after a successful session disconnects, in both cases
|
||||
// before the next reconnect attempt.
|
||||
func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pool *SessionPool) {
|
||||
for {
|
||||
select {
|
||||
@@ -198,7 +199,7 @@ func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.
|
||||
}
|
||||
|
||||
ps := pool.Add(id, smuxSess)
|
||||
deps.log().Errorf("[session %d] connected (active: %d)", id, pool.Count())
|
||||
deps.log().Infof("[session %d] connected (active: %d)", id, pool.Count())
|
||||
|
||||
for !smuxSess.IsClosed() {
|
||||
select {
|
||||
@@ -212,7 +213,7 @@ func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.
|
||||
|
||||
pool.Remove(ps)
|
||||
cleanup()
|
||||
deps.log().Errorf("[session %d] disconnected (active: %d), reconnecting...", id, pool.Count())
|
||||
deps.log().Infof("[session %d] disconnected (active: %d), reconnecting...", id, pool.Count())
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sync"
|
||||
@@ -37,12 +36,13 @@ var packetPool = sync.Pool{
|
||||
New: func() any { return &Packet{Data: make([]byte, 2048)} },
|
||||
}
|
||||
|
||||
// GetCredsFunc is an alias of common.GetCredsFunc kept for cmd/main wiring
|
||||
// stability.
|
||||
// GetCredsFunc is re-exported from common so callers can keep their imports
|
||||
// scoped to this package.
|
||||
type GetCredsFunc = common.GetCredsFunc
|
||||
|
||||
// AuthHandler is the subset of vkauth.Client this package needs. Keeping it as
|
||||
// an interface lets internal/proxy/udprelay avoid importing internal/client/vkauth.
|
||||
// AuthHandler is the subset of vkauth.Client this package needs. Defined as
|
||||
// an interface so tests can inject fakes; the production wiring still imports
|
||||
// vkauth for its sentinel errors (ErrFatalCaptchaNoStreams, etc.).
|
||||
type AuthHandler interface {
|
||||
IsAuthError(err error) bool
|
||||
HandleAuthError(streamID int) bool
|
||||
@@ -84,10 +84,10 @@ func (d *Deps) log() logx.Logger {
|
||||
// connectedStreams is owned by the caller (vkauth reads it via StreamsAlive)
|
||||
// and incremented/decremented by oneTURN.
|
||||
// Returns after all stream loops exit (i.e. when ctx is cancelled).
|
||||
func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, logger logx.Logger, connectedStreams *atomic.Int32, appCancel context.CancelFunc, params *Params, peer *net.UDPAddr, listenAddr string, numStreams int) {
|
||||
func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, logger logx.Logger, connectedStreams *atomic.Int32, appCancel context.CancelFunc, params *Params, peer *net.UDPAddr, listenAddr string, numStreams int) error {
|
||||
listenConn, err := net.ListenPacket("udp", listenAddr)
|
||||
if err != nil {
|
||||
log.Panicf("Failed to listen: %s", err)
|
||||
return fmt.Errorf("udprelay listen %s: %w", listenAddr, err)
|
||||
}
|
||||
context.AfterFunc(ctx, func() {
|
||||
if closeErr := listenConn.Close(); closeErr != nil {
|
||||
@@ -141,6 +141,7 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
const inboundQueueCap = 2000
|
||||
@@ -235,10 +236,16 @@ func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
c := make(chan error)
|
||||
c := make(chan error, 1)
|
||||
go oneTURN(ctx, deps, params, peer, conn2, streamID, c)
|
||||
|
||||
if err := <-c; err != nil {
|
||||
var err error
|
||||
select {
|
||||
case err = <-c:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, vkauth.ErrFatalCaptchaNoStreams) {
|
||||
deps.log().Errorf("[STREAM %d] Fatal manual captcha error. Shutting down application.", streamID)
|
||||
if deps.AppCancel != nil {
|
||||
@@ -268,7 +275,11 @@ func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr
|
||||
}
|
||||
} else {
|
||||
deps.log().Errorf("[STREAM %d] %s", streamID, err)
|
||||
time.Sleep(2 * time.Second)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -303,9 +314,9 @@ func oneDTLS(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net.
|
||||
if closeErr := dtlsConn.Close(); closeErr != nil {
|
||||
deps.log().Errorf("[STREAM %d] failed to close DTLS connection: %s", streamID, closeErr)
|
||||
}
|
||||
deps.log().Errorf("[STREAM %d] Closed DTLS connection\n", streamID)
|
||||
deps.log().Infof("[STREAM %d] Closed DTLS connection", streamID)
|
||||
}()
|
||||
deps.log().Errorf("[STREAM %d] Established DTLS connection!\n", streamID)
|
||||
deps.log().Infof("[STREAM %d] Established DTLS connection", streamID)
|
||||
|
||||
if okchan != nil {
|
||||
go func() {
|
||||
@@ -387,9 +398,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
}
|
||||
}()
|
||||
|
||||
if deps.log().DebugEnabled() {
|
||||
deps.log().Errorf("[STREAM %d] relayed-address=%s", streamID, relayConn.LocalAddr().String())
|
||||
}
|
||||
deps.log().Debugf("[STREAM %d] relayed-address=%s", streamID, relayConn.LocalAddr().String())
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
turnctx, turncancel := context.WithCancel(ctx)
|
||||
@@ -409,7 +418,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
wg.Go(func() {
|
||||
defer turncancel()
|
||||
buf := make([]byte, 1600)
|
||||
var wireBuf []byte
|
||||
@@ -446,7 +455,7 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
})
|
||||
|
||||
wg.Go(func() {
|
||||
defer turncancel()
|
||||
|
||||
@@ -204,17 +204,21 @@ func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) {
|
||||
dataShards, parityShards := selectedFEC()
|
||||
|
||||
if isServer {
|
||||
// Server: listen on the PacketConn and accept one session
|
||||
// Server: listen on the PacketConn, accept one session, then drop the
|
||||
// listener (it owns the PacketConn — the accepted session keeps using
|
||||
// it via the shared kcp mux).
|
||||
var listener *kcp.Listener
|
||||
listener, err = kcp.ServeConn(block, dataShards, parityShards, pc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = listener.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, err
|
||||
}
|
||||
sess, err = listener.AcceptKCP()
|
||||
if err != nil {
|
||||
_ = listener.Close()
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -156,6 +156,8 @@ func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
}
|
||||
|
||||
// Unwrap decodes a wire packet into dst and returns the plaintext length.
|
||||
// Note: the AEAD opens in-place inside wire, so callers must treat wire as
|
||||
// consumed after this call (do not reuse its contents).
|
||||
func (c *Conn) Unwrap(wire, dst []byte) (int, error) {
|
||||
if len(wire) < Overhead {
|
||||
return 0, errors.New("wrap: packet too short")
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
# Независимый аудит — 2026-05-19
|
||||
|
||||
Аудит проведён без опоры на предыдущие AUDIT_* и без учёта обратной совместимости.
|
||||
Билд чистый, `go vet` / `golangci-lint run` без замечаний. Дефекты ниже не ловятся
|
||||
текущими тулзами.
|
||||
|
||||
## 1. Архитектура
|
||||
|
||||
- **`cmd/vk-turn-server/main.go` 396 LoC**: `handleUDPConnection`, `handleVLESSConnection`,
|
||||
`pipeConn`, `prefixedConn` — бизнес-логика. Должны переехать в `internal/proxy/...`.
|
||||
Клиент симметрично уже сделан (`tcpfwd.Run`), сервер отстал.
|
||||
- **Глобалы в server main** (`cmd/vk-turn-server/main.go:27-30`): `logger`,
|
||||
`globalBondRegistry`. Mutable package-vars вместо передачи через стек.
|
||||
- **Asymmetry клиента**: UDP-режим разворачивается inline в
|
||||
`cmd/vk-turn-client/main.go:157-261`. Должен быть `udprelay.Run(...)` симметрично
|
||||
`tcpfwd.Run(...)`.
|
||||
- **Лишние `Deps`-структуры**: bondserver/bondclient/udprelay/tcpfwd. Большая часть
|
||||
содержит только Logger + 1-2 поля. Три разных стиля инициализации.
|
||||
- **Captcha-пакет монолит**: `manual.go` 892 / `slider.go` 627 / `captcha.go` 579 —
|
||||
смешаны HTTP-flow, parsing, PoW-mining, fingerprinting.
|
||||
- **`internal/proxy/common`** существует ради 2 функций (`DialTURN`, `NewClientWrap`).
|
||||
Слить в `turndial`.
|
||||
|
||||
## 2. Корректность / баги
|
||||
|
||||
- **`internal/proxy/udprelay/udprelay.go:96`** — `strings.Contains(err.Error(), "context deadline exceeded")`.
|
||||
Match по строке стандартной ошибки. Должно быть `errors.Is(err, context.DeadlineExceeded)`.
|
||||
Tight-loop risk: ветка `continue` без backoff если oneDTLS быстро возвращает DeadlineExceeded.
|
||||
- **`internal/proxy/udprelay/udprelay.go:170-178`** — бесконечная публикация одного
|
||||
и того же `conn2` в `connchan`. TURNLoop читает один раз. Должно быть одноразово.
|
||||
- **`internal/proxy/bondserver/bondserver.go:269`** — `pending` map без лимита, DoS-risk
|
||||
при дырах в seq. У клиента лимит 1024 есть (`bondclient.go:240`).
|
||||
- **`internal/client/vkauth/token.go:168-202`** — `context.WithTimeout(context.Background(), 3m)`
|
||||
для manual captcha. При отмене parent ctx goroutine `c.manualSolve(...)` живёт 3 мин.
|
||||
Goroutine-leak на shutdown.
|
||||
- **`internal/client/captcha/captcha.go:466`** — `solveCaptchaPoW` ctx-check каждые 4096
|
||||
итераций. Cancel может опоздать на сотни мс.
|
||||
- **`internal/wire/srtpmimicry/relay.go:22,38`** — `make([]byte, MaxWire(...))` на каждый
|
||||
ReadFrom/WriteTo. На горячем пути UDP — GC давление. В `listen.go` есть `bufPool`.
|
||||
- **`internal/client/captcha/captcha.go:47`** — `captchaDebugCache sync.Map` без TTL/eviction.
|
||||
- **`internal/client/vkauth/token.go:36`** — `tlsclient.NewHttpClient` пересоздаётся
|
||||
внутри `getTokenChain` на каждую попытку.
|
||||
- **`cmd/vk-turn-server/main.go:209,219,240,250`** — magic `time.Minute*30` для
|
||||
read/write deadline. Bidir UDP-relay с 30-минутным dead-timeout повисает при простое.
|
||||
- **`internal/client/vkauth/client.go:213-238`** — sentinel-errors через
|
||||
`strings.Contains(err.Error(), "...")`. Хрупко.
|
||||
|
||||
## 3. Stale-комментарии (refactor-history протёк в godoc)
|
||||
|
||||
- `internal/proxy/tcpfwd/tcpfwd.go:38-39` — "Bond client lives in main during stage 4.2;
|
||||
it will move to internal/bond/client in stage 5.1". Уже мигрировано.
|
||||
- `internal/proxy/tcpfwd/pool.go:6` — "bond client half (still living in main during
|
||||
refactor stage 4.2)". Ложь.
|
||||
- `internal/proxy/common/common.go:2-4` — ссылка на `notes/AUDIT_2026-05-19_V2.md`,
|
||||
файл удалён.
|
||||
- `internal/config/config.go:7-10` — "V2-7: options are grouped by domain...".
|
||||
Стадия рефакторинга в публичном godoc.
|
||||
- `internal/proxy/udprelay/udprelay.go:54-55` — "Equivalent of the old
|
||||
client/main.go turnParams". Историческая ссылка.
|
||||
- `cmd/vk-turn-client/main.go:1-2` — `SPDX-FileCopyrightText: 2023 The Pion community`
|
||||
на основном proxy main. Ложный copyright.
|
||||
- `internal/logx/logx.go:1-4` — описывает что заменило, а не что есть.
|
||||
- `internal/proxy/bondclient/bondclient.go:3-4` — "Frame wire-format lives in internal/bond"
|
||||
→ должно быть `internal/wire/bondframe`.
|
||||
|
||||
## 4. Нейминг
|
||||
|
||||
- `internal/wire/bondframe/bondframe.go:1` — godoc `// Package bond ...`, пакет `bondframe`.
|
||||
- `srtpmimicry.Conn` — AEAD-кодек, не `net.Conn`. Лучше `Cipher`/`Codec`.
|
||||
- `kcptun.DtlsPacketConn` / `NewDtlsPacketConn` — экспортированы, используются только внутри.
|
||||
- `udprelay.Pool` — глобальная `sync.Pool` экспортирована, никто извне не дёргает.
|
||||
- `bondclient.lane.dead atomic.Bool` vs `bondserver` slice-search remove — разные стили.
|
||||
- `turndial.Stream` vs `tcpfwd.PooledSession` — концептуальное пересечение.
|
||||
- `connchan` / `okchan` / `cchan` в client/main.go — нечитаемо.
|
||||
- Magic numbers: `2000` (inboundChan), `1024` (recvCh), 4 MiB vs 16 KiB чтение/запись фрейма.
|
||||
|
||||
## 5. Прочее
|
||||
|
||||
- 134 прямых `log.Printf` в 13 файлах при наличии `logx.Logger`. Mix — нельзя
|
||||
глобально перенаправить вывод.
|
||||
- `selfsign.GenerateSelfSigned()` на каждый `dtlsdial.Dial`. Кэшируй.
|
||||
- Hardcoded VK secrets `internal/client/vkauth/types.go:21-27` (известно).
|
||||
- Нет тестов: `bondclient`, `tcpfwd`, `udprelay`, `captcha/captcha.go` (auto-solver),
|
||||
`captcha/slider.go`. Самые гоночные компоненты без тестов.
|
||||
- Артефакты в репо: `client.exe`, `server.exe`, `libvkturn.so` — в `.gitignore` нет.
|
||||
|
||||
## Приоритеты исправлений
|
||||
|
||||
1. **Bugs (P0):**
|
||||
1.1. `udprelay`: `errors.Is(DeadlineExceeded)` вместо string-match + одноразовый conn2 + backoff.
|
||||
1.2. `bondserver`: cap `pending`.
|
||||
1.3. `srtpmimicry.RelayPacketConn`: bufPool как в listen.go.
|
||||
1.4. Goroutine-leak `manualSolve` (на shutdown).
|
||||
|
||||
2. **Stale-комменты / нейминг (P1):**
|
||||
2.1. Убрать stage-4.2 / V2-* / notes/AUDIT_2026-05-19_V2.md / Pion-copyright / "Package bond".
|
||||
2.2. Stale ссылка `internal/bond` → `internal/wire/bondframe`.
|
||||
|
||||
3. **Sentinel errors (P1):** `var ErrXxx = errors.New(...)` + `errors.Is`.
|
||||
|
||||
4. **Server-main → internal (P2):** вынести handle*Connection / pipeConn / prefixedConn,
|
||||
убрать глобалы.
|
||||
|
||||
5. **`udprelay.Run(...)` симметрично tcpfwd.Run (P2).**
|
||||
|
||||
6. **Logger unification (P2):** заменить `log.Printf` на `logx.Logger`.
|
||||
|
||||
7. **`.gitignore`:** `*.exe`, `*.so`.
|
||||
Reference in new issue
Block a user