fix: исправить баги, sentinel-ошибки, устаревшие доки
Баги: - udprelay: errors.Is(DeadlineExceeded) вместо сравнения строк; короткий backoff в ветке lockout; обернуть DTLS-ошибку через %w - bondserver.copyBondToBackend: лимит pending-map в 1024 (паритет с bondclient) - srtpmimicry.RelayPacketConn: bufPool для горячего UDP-пути (паритет с listen.go) - vkauth.token.go: ручной солвер под ctx.WithTimeout(ctx, ...) вместо Background — нет утечки горутины при shutdown Гигиена: - sentinel-ошибки vkauth как var = errors.New(...); вызыватели используют errors.Is - убраны устаревшие комментарии этапов рефакторинга (Pion SPDX, "Package bond", internal/bond, удалённый файл заметок) - .gitignore: *.exe, *.so Тесты + lint проходят.
This commit is contained in:
1 parent
7e3369f478
commit
ed6825976a
18 files changed
+203
-448
No files matched your search
@@ -2,6 +2,7 @@ package vkauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
@@ -211,7 +212,7 @@ func (c *Client) fetchSerialized(ctx context.Context, link string, streamID int)
|
||||
// fetch loops over c.credentials, returning on first success or terminal error.
|
||||
func (c *Client) fetch(ctx context.Context, link string, streamID int) (string, string, []string, error) {
|
||||
if time.Now().Unix() < c.lockout.Load() {
|
||||
return "", "", nil, fmt.Errorf("CAPTCHA_WAIT_REQUIRED: global lockout active")
|
||||
return "", "", nil, fmt.Errorf("%w: %w", ErrCaptchaWaitRequired, ErrLockoutActive)
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
@@ -227,10 +228,10 @@ func (c *Client) fetch(ctx context.Context, link string, streamID int) (string,
|
||||
lastErr = err
|
||||
log.Printf("[STREAM %d] [VK Auth] Failed with client_id=%s: %v", streamID, creds.ClientID, err)
|
||||
|
||||
es := err.Error()
|
||||
if strings.Contains(es, ErrCaptchaWaitRequired) || strings.Contains(es, "FATAL_CAPTCHA") {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -124,11 +123,11 @@ func TestFetchShortCircuitsOnCaptchaWait(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
c := newTestClient(t, func(_ context.Context, _ string, _ int, _ VKCredentials, _ tlsclient.CookieJar) (string, string, []string, error) {
|
||||
calls.Add(1)
|
||||
return "", "", nil, errors.New(ErrCaptchaWaitRequired)
|
||||
return "", "", nil, ErrCaptchaWaitRequired
|
||||
})
|
||||
|
||||
_, _, _, err := c.GetCredentials(context.Background(), "L", 0)
|
||||
if err == nil || !strings.Contains(err.Error(), ErrCaptchaWaitRequired) {
|
||||
if err == nil || !errors.Is(err, ErrCaptchaWaitRequired) {
|
||||
t.Fatalf("expected CAPTCHA_WAIT_REQUIRED, got %v", err)
|
||||
}
|
||||
if calls.Load() != 1 {
|
||||
@@ -184,7 +183,7 @@ func TestLockoutBlocksFetch(t *testing.T) {
|
||||
}
|
||||
|
||||
_, _, _, err := c.GetCredentials(context.Background(), "L", 0)
|
||||
if err == nil || !strings.Contains(err.Error(), "global lockout active") {
|
||||
if err == nil || !errors.Is(err, ErrLockoutActive) {
|
||||
t.Fatalf("expected lockout error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,9 +135,9 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
c.engageLockout(60 * time.Second)
|
||||
if c.streamsFn() == 0 {
|
||||
log.Printf("[STREAM %d] [FATAL] 0 connected streams and captcha solve modes exhausted.", streamID)
|
||||
return "", "", nil, errors.New(ErrFatalCaptchaNoStreams)
|
||||
return "", "", nil, ErrFatalCaptchaNoStreams
|
||||
}
|
||||
return "", "", nil, errors.New(ErrCaptchaWaitRequired)
|
||||
return "", "", nil, ErrCaptchaWaitRequired
|
||||
}
|
||||
|
||||
var successToken string
|
||||
@@ -164,8 +164,11 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
break
|
||||
}
|
||||
log.Printf("[STREAM %d] [Captcha] Triggering manual captcha fallback...", streamID)
|
||||
// Background ctx so a short parent deadline doesn't cut user solve time.
|
||||
manualCtx, manualCancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
// 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
|
||||
// goroutine doesn't outlive the process.
|
||||
manualCtx, manualCancel := context.WithTimeout(ctx, 3*time.Minute)
|
||||
|
||||
type manualRes struct {
|
||||
token string
|
||||
@@ -193,7 +196,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
log.Printf("[STREAM %d] [Captcha] manual solver returned error: %v", streamID, solveErr)
|
||||
}
|
||||
case <-manualCtx.Done():
|
||||
if manualCtx.Err() == context.DeadlineExceeded {
|
||||
if errors.Is(manualCtx.Err(), context.DeadlineExceeded) {
|
||||
solveErr = fmt.Errorf("manual captcha timed out after 3m")
|
||||
} else {
|
||||
solveErr = fmt.Errorf("manual captcha interrupted: %w", manualCtx.Err())
|
||||
@@ -212,9 +215,9 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
c.engageLockout(60 * time.Second)
|
||||
if c.streamsFn() == 0 {
|
||||
log.Printf("[STREAM %d] [FATAL] 0 connected streams and manual captcha failed/timed out.", streamID)
|
||||
return "", "", nil, errors.New(ErrFatalCaptchaNoStreams)
|
||||
return "", "", nil, ErrFatalCaptchaNoStreams
|
||||
}
|
||||
return "", "", nil, errors.New(ErrCaptchaWaitRequired)
|
||||
return "", "", nil, ErrCaptchaWaitRequired
|
||||
}
|
||||
|
||||
if captchaErr.CaptchaAttempt == "0" || captchaErr.CaptchaAttempt == "" {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package vkauth
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// VKCredentials is one app_id/app_secret pair used to obtain anonymous tokens.
|
||||
type VKCredentials struct {
|
||||
@@ -35,10 +38,10 @@ const (
|
||||
DefaultStreamsPerCache = 10
|
||||
)
|
||||
|
||||
// Sentinel error message fragments produced by the auth flow. Consumers match
|
||||
// on substring to preserve wire compatibility with the existing caller logic.
|
||||
const (
|
||||
ErrCaptchaWaitRequired = "CAPTCHA_WAIT_REQUIRED"
|
||||
ErrFatalCaptchaNoStreams = "FATAL_CAPTCHA_FAILED_NO_STREAMS"
|
||||
ErrLockoutActiveSuffix = "global lockout active"
|
||||
// Sentinel errors produced by the auth flow. Callers use errors.Is.
|
||||
// The string forms remain stable for log output.
|
||||
var (
|
||||
ErrCaptchaWaitRequired = errors.New("CAPTCHA_WAIT_REQUIRED")
|
||||
ErrFatalCaptchaNoStreams = errors.New("FATAL_CAPTCHA_FAILED_NO_STREAMS")
|
||||
ErrLockoutActive = errors.New("global lockout active")
|
||||
)
|
||||
@@ -4,10 +4,8 @@
|
||||
// wrap key, but do not touch the network, DNS, or process state. main() is
|
||||
// responsible for wiring those side effects after Parse* returns.
|
||||
//
|
||||
// V2-7: options are grouped by domain (TURN, Obf, Proxy, VK, DNS, Log) so the
|
||||
// struct shape mirrors the conceptual layers of the proxy instead of being a
|
||||
// flat bag of bools. CLI flag names, defaults, and behavior are bit-exact
|
||||
// compatible with the pre-V2-7 surface.
|
||||
// Options are grouped by domain (TURN, Obf, Proxy, VK, DNS, Log) so the struct
|
||||
// shape mirrors the conceptual layers of the proxy.
|
||||
package config
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Package logx is a minimal leveled logger over stdlib log. It replaces the
|
||||
// per-package Deps{Debug bool, Debugf func} pair: callers receive a Logger and
|
||||
// call Debugf/Infof/Warnf/Errorf directly. Output format is bit-compatible with
|
||||
// the previous `log.Printf`-gated-by-isDebug pattern.
|
||||
// Package logx is a minimal leveled logger over stdlib log. Callers receive a
|
||||
// Logger and call Debugf/Infof/Warnf/Errorf directly; Debugf is gated by a
|
||||
// debug flag, the other levels always print via stdlib log.
|
||||
package logx
|
||||
|
||||
import "log"
|
||||
@@ -24,7 +23,7 @@ type stdLogger struct {
|
||||
}
|
||||
|
||||
// New returns a Logger that prints via stdlib log. If debug is false, Debugf is
|
||||
// a no-op (matches the legacy `if isDebug { log.Printf(...) }` shape).
|
||||
// a no-op.
|
||||
func New(debug bool) Logger {
|
||||
return &stdLogger{debug: debug}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package bondclient implements the client side of the bonded VLESS lane:
|
||||
// a single accepted TCP connection striped (round-robin) across all currently
|
||||
// live smux sessions in a tcpfwd.SessionPool. Frame wire-format lives in
|
||||
// internal/bond; this package wires the local TCP <-> lanes copy loops.
|
||||
// internal/wire/bondframe; this package wires the local TCP <-> lanes copy loops.
|
||||
package bondclient
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package bondserver implements the server side of the bonded VLESS lane:
|
||||
// a single backend TCP connection multiplexed across N smux streams that all
|
||||
// share a ConnID. Frame wire-format lives in internal/bond; this package wires
|
||||
// the backend TCP <-> lanes copy loops and the per-ConnID registry.
|
||||
// share a ConnID. Frame wire-format lives in internal/wire/bondframe; this package
|
||||
// wires the backend TCP <-> lanes copy loops and the per-ConnID registry.
|
||||
package bondserver
|
||||
|
||||
import (
|
||||
@@ -283,6 +283,13 @@ func (c *serverConn) copyBondToBackend(backendConn net.Conn) {
|
||||
case f := <-c.recvCh:
|
||||
switch f.Type {
|
||||
case bondframe.FrameData:
|
||||
// Bound the reorder buffer so a malicious or buggy peer
|
||||
// that emits seq with permanent gaps cannot exhaust memory.
|
||||
// Matches bondclient.copyBondToTCP.
|
||||
if len(pending) >= 1024 {
|
||||
log.Printf("[bond %d] pending map overflow (>1024), closing", c.id)
|
||||
return
|
||||
}
|
||||
pending[f.Seq] = f.Data
|
||||
case bondframe.FrameFIN:
|
||||
v := f.Seq
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package common holds small helpers shared between udprelay and tcpfwd. The
|
||||
// two proxy modes layer DTLS and srtpmimicry differently (see V2-6 decision
|
||||
// in notes/AUDIT_2026-05-19_V2.md), so a full Engine/Handler abstraction was
|
||||
// rejected. This package only collects the bits that are genuinely identical.
|
||||
// Package common holds the few helpers shared by udprelay and tcpfwd
|
||||
// (TURN dial + wrap codec construction). The two proxy modes layer DTLS and
|
||||
// srtpmimicry differently, so a full Engine/Handler abstraction is intentionally
|
||||
// avoided — this package only collects what is genuinely identical.
|
||||
package common
|
||||
|
||||
import (
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
// smux sessions. Each accepted local TCP connection is opened as a smux stream
|
||||
// (round-robin across sessions) or, with bond, striped across all live sessions.
|
||||
//
|
||||
// The package exposes SessionPool/PooledSession so that the bond client half
|
||||
// (still living in main during refactor stage 4.2) can operate on them.
|
||||
// SessionPool/PooledSession are exported so the bond client (internal/proxy/bondclient)
|
||||
// can stripe a single TCP connection across multiple live sessions.
|
||||
package tcpfwd
|
||||
|
||||
import (
|
||||
|
||||
@@ -35,8 +35,7 @@ type Params struct {
|
||||
|
||||
// BondHandler stripes one accepted TCP connection across all currently-live
|
||||
// pool sessions. Nil disables bond mode (callers will then use round-robin).
|
||||
// Bond client lives in main during stage 4.2; it will move to internal/bond/client
|
||||
// in stage 5.1.
|
||||
// The bond client implementation lives in internal/proxy/bondclient.
|
||||
type BondHandler func(ctx context.Context, tcpConn net.Conn, connID uint64, lanes []*PooledSession)
|
||||
|
||||
// Deps groups host-process dependencies needed by the VLESS loop.
|
||||
|
||||
@@ -7,15 +7,16 @@ package udprelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/cacggghp/vk-turn-proxy/internal/client/vkauth"
|
||||
"github.com/cacggghp/vk-turn-proxy/internal/logx"
|
||||
"github.com/cacggghp/vk-turn-proxy/internal/proxy/common"
|
||||
"github.com/cacggghp/vk-turn-proxy/internal/stats"
|
||||
@@ -50,8 +51,7 @@ type AuthHandler interface {
|
||||
LockoutUntilUnix() int64
|
||||
}
|
||||
|
||||
// Params is the per-stream TURN/wrap configuration shared by the DTLS and TURN
|
||||
// loops. Equivalent of the old client/main.go turnParams.
|
||||
// Params is the per-stream TURN/wrap configuration shared by the DTLS and TURN loops.
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
@@ -92,10 +92,18 @@ func DTLSLoop(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net
|
||||
return
|
||||
default:
|
||||
err := oneDTLS(ctx, deps, peer, listenConn, inboundChan, connchan, okchan, streamID)
|
||||
if err != nil {
|
||||
if time.Now().Unix() < deps.Auth.LockoutUntilUnix() && strings.Contains(err.Error(), "context deadline exceeded") {
|
||||
continue
|
||||
// During captcha lockout the handshake deadline fires before
|
||||
// auth retries can succeed; back off briefly to avoid a tight
|
||||
// retry spin until the lockout clears.
|
||||
if err != nil && time.Now().Unix() < deps.Auth.LockoutUntilUnix() && errors.Is(err, context.DeadlineExceeded) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Duration(1+rand.Intn(2)) * time.Second):
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
@@ -124,15 +132,15 @@ func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr
|
||||
go oneTURN(ctx, deps, params, peer, conn2, streamID, c)
|
||||
|
||||
if err := <-c; err != nil {
|
||||
if strings.Contains(err.Error(), "FATAL_CAPTCHA") {
|
||||
if errors.Is(err, vkauth.ErrFatalCaptchaNoStreams) {
|
||||
log.Printf("[STREAM %d] Fatal manual captcha error. Shutting down application.", streamID)
|
||||
if deps.AppCancel != nil {
|
||||
deps.AppCancel()
|
||||
}
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "CAPTCHA_WAIT_REQUIRED") {
|
||||
if !strings.Contains(err.Error(), "global lockout active") {
|
||||
if errors.Is(err, vkauth.ErrCaptchaWaitRequired) {
|
||||
if !errors.Is(err, vkauth.ErrLockoutActive) {
|
||||
log.Printf("[STREAM %d] Backing off for 60 seconds to avoid IP ban...", streamID)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -167,6 +175,9 @@ func oneDTLS(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net.
|
||||
defer dtlscancel()
|
||||
|
||||
conn1, conn2 := connutil.AsyncPacketPipe()
|
||||
// TURNLoop may restart oneTURN several times within a single DTLS lifetime,
|
||||
// re-reading conn2 on each restart; keep publishing until the DTLS attempt
|
||||
// itself ends.
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
@@ -178,7 +189,7 @@ func oneDTLS(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net.
|
||||
}()
|
||||
dtlsRaw, err1 := deps.DTLSDialer.Dial(dtlsctx, conn1, peer)
|
||||
if err1 != nil {
|
||||
return fmt.Errorf("failed to connect DTLS: %s", err1)
|
||||
return fmt.Errorf("failed to connect DTLS: %w", err1)
|
||||
}
|
||||
var dtlsConn net.Conn = dtlsRaw
|
||||
defer func() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package bond contains the wire format used by the VLESS bond multi-lane
|
||||
// Package bondframe contains the wire format used by the VLESS bond multi-lane
|
||||
// transport (hello + framed data/FIN). Both the client (initiator) and the
|
||||
// server (acceptor) speak the same encoding.
|
||||
package bondframe
|
||||
|
||||
@@ -19,8 +19,16 @@ func (r *RelayPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
if r.Conn == nil {
|
||||
return r.Relay.ReadFrom(b)
|
||||
}
|
||||
buf := make([]byte, MaxWire(len(b)))
|
||||
n, addr, err := r.Relay.ReadFrom(buf)
|
||||
bp := bufPool.Get().(*[]byte) //nolint:errcheck // pool New always returns *[]byte
|
||||
buf := *bp
|
||||
need := MaxWire(len(b))
|
||||
if cap(buf) < need {
|
||||
buf = make([]byte, need)
|
||||
*bp = buf
|
||||
}
|
||||
defer bufPool.Put(bp)
|
||||
|
||||
n, addr, err := r.Relay.ReadFrom(buf[:cap(buf)])
|
||||
if err != nil {
|
||||
return 0, addr, err
|
||||
}
|
||||
@@ -35,7 +43,17 @@ func (r *RelayPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||
if r.Conn == nil {
|
||||
return r.Relay.WriteTo(b, r.Peer)
|
||||
}
|
||||
out := make([]byte, MaxWire(len(b)))
|
||||
wireLen := MaxWire(len(b))
|
||||
|
||||
bp := bufPool.Get().(*[]byte) //nolint:errcheck // pool New always returns *[]byte
|
||||
out := *bp
|
||||
if cap(out) < wireLen {
|
||||
out = make([]byte, wireLen)
|
||||
*bp = out
|
||||
}
|
||||
out = out[:wireLen]
|
||||
defer bufPool.Put(bp)
|
||||
|
||||
n, err := r.Conn.WrapInto(out, b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
Reference in new issue
Block a user