Выпуск WDTT Plus v19

This commit is contained in:
Ivan4537 committed 2026-09-29 10:52:29 +03:00
1 parent af0ff89108
commit ed8893a2a6
143 files changed
+15817 -3821

No files matched your search

+466
View File
@@ -0,0 +1,466 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"strings"
"sync"
"time"
)
// Connection selection is independent of the server's packet framing. A
// candidate is accepted only after authenticated GETCONF and a relay reply.
// There is one discovery attempt for the entire client, not one per worker.
const connectionAttemptBudget = 12
const connectionVerifiedStartLimit = 3
type connectionPath struct {
endpoint turnEndpoint
masque warpMasqueProtocol
front string
}
func (p connectionPath) kind() string {
if p.masque == warpMasqueHTTP2 {
return "h2"
}
if p.masque == warpMasqueHTTP3 {
return "h3"
}
if p.front != "" {
return "tls-front"
}
return string(p.endpoint.Transport)
}
func (p connectionPath) key() string { return p.endpoint.key() + "|" + p.kind() }
type connectionPolicy struct {
mu sync.Mutex
preferred string
noUDP bool
active, pending, failures int
blocked, sleeping, paused bool
epoch uint64
next time.Time
udpRetryAfter time.Time
excluded map[string]time.Time
changed chan struct{}
probes map[*connectionLease]struct{}
readyPaths map[string]int
readyKinds map[string]int
}
func newConnectionPolicy(preferred string, noUDP bool) *connectionPolicy {
return &connectionPolicy{preferred: preferred, noUDP: noUDP, excluded: make(map[string]time.Time), changed: make(chan struct{}), probes: make(map[*connectionLease]struct{}), readyPaths: make(map[string]int), readyKinds: make(map[string]int)}
}
func (a *connectionPolicy) configure(preferred string, noUDP bool) {
a.mu.Lock()
defer a.mu.Unlock()
// Android may report a handover while flags/startup secrets are loading.
// The command-line hint belongs exclusively to the original network.
if a.epoch == 0 {
a.preferred = preferred
}
a.noUDP = noUDP
}
func (a *connectionPolicy) deferUDP(delay time.Duration) {
a.mu.Lock()
defer a.mu.Unlock()
if delay > 0 {
a.udpRetryAfter = time.Now().Add(delay)
}
}
func (a *connectionPolicy) pathAllowed(p connectionPath, now time.Time) bool {
datagram := p.kind() == "udp" || p.kind() == "h3"
return !datagram || (!a.noUDP && !now.Before(a.udpRetryAfter))
}
func (a *connectionPolicy) notifyLocked() { close(a.changed); a.changed = make(chan struct{}) }
func (a *connectionPolicy) waitAvailable(ctx context.Context) error {
for {
if err := ctx.Err(); err != nil {
return err
}
a.mu.Lock()
available, changed := !a.blocked && !a.sleeping && !a.paused, a.changed
a.mu.Unlock()
if available {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-changed:
}
}
}
func (a *connectionPolicy) command(command string) {
a.mu.Lock()
defer a.mu.Unlock()
switch command {
case "CONNECTION_NETWORK":
a.epoch++
a.failures = 0
a.paused = false
a.preferred = ""
a.excluded = make(map[string]time.Time)
a.readyPaths = make(map[string]int)
a.readyKinds = make(map[string]int)
case "CONNECTION_OFFLINE":
a.blocked = true
case "CONNECTION_ONLINE":
a.blocked = false
case "DEVICE_SLEEP", "PAUSE":
a.sleeping = true
case "DEVICE_WAKE", "RESUME":
a.sleeping = false
default:
return
}
if a.sleeping || a.blocked || command == "CONNECTION_NETWORK" {
for lease := range a.probes {
lease.interrupted = true
if lease.cancel != nil {
lease.cancel()
}
}
}
a.notifyLocked()
}
func connectionPaths(endpoints []turnEndpoint, tp *TurnParams, noUDP bool) []connectionPath {
paths := make([]connectionPath, 0, len(endpoints)*3)
for _, e := range endpoints {
if e.Transport == turnTransportUDP {
continue
}
paths = append(paths, connectionPath{endpoint: e})
if e.Transport == turnTransportTLS && tp.TLSFrontSNI != "" {
paths = append(paths, connectionPath{endpoint: e, front: tp.TLSFrontSNI})
}
}
if tp.Masque != nil {
for _, protocol := range []warpMasqueProtocol{warpMasqueHTTP2, warpMasqueHTTP3} {
if noUDP && protocol == warpMasqueHTTP3 {
continue
}
for _, e := range endpoints {
if e.Transport != turnTransportUDP {
paths = append(paths, connectionPath{endpoint: e, masque: protocol})
}
}
}
}
if !noUDP {
for _, e := range endpoints {
if e.Transport == turnTransportUDP {
paths = append(paths, connectionPath{endpoint: e})
}
}
}
// Interleave transport classes, so many dead addresses of one class do
// not consume the complete budget before another transport gets a chance.
var result []connectionPath
for round := 0; ; round++ {
added := false
for _, kind := range []string{"udp", "tls", "tls-front", "tcp", "h2", "h3"} {
n := 0
for _, p := range paths {
if p.kind() != kind {
continue
}
if n == round {
result = append(result, p)
added = true
break
}
n++
}
}
if !added {
return result
}
}
}
type connectionLease struct {
a *connectionPolicy
path connectionPath
epoch uint64
ready bool
cancel context.CancelFunc
interrupted bool
finished bool
stage string
started time.Time
}
func (l *connectionLease) bind(cancel context.CancelFunc) {
l.a.mu.Lock()
defer l.a.mu.Unlock()
l.cancel = cancel
if l.interrupted {
cancel()
}
}
func (l *connectionLease) setStage(stage string) {
l.a.mu.Lock()
defer l.a.mu.Unlock()
l.stage = stage
}
func (a *connectionPolicy) acquire(ctx context.Context, paths []connectionPath) (*connectionLease, error) {
if len(paths) == 0 {
return nil, fmt.Errorf("нет разрешённых путей подключения")
}
for {
if err := ctx.Err(); err != nil {
return nil, err
}
a.mu.Lock()
now := time.Now()
index := -1
for i, p := range paths {
if !a.pathAllowed(p, now) || now.Before(a.excluded[p.key()]) {
continue
}
if index < 0 {
index = i
}
if p.kind() == a.preferred {
index = i
break
}
}
// A new transport still has one discovery probe. Once a worker on
// this network has confirmed it, match the existing DTLS limit of 3.
limit := 1
if index >= 0 && a.readyKinds[paths[index].kind()] > 0 {
limit = connectionVerifiedStartLimit
}
if a.failures >= connectionAttemptBudget && a.active == 0 && !a.paused {
a.paused = true
log.Print("[CONNECTION] PAUSED Лимит попыток исчерпан. Смените сеть или подключитесь заново.")
}
if !a.blocked && !a.sleeping && !a.paused && a.pending < limit && !now.Before(a.next) {
if index >= 0 {
a.pending++
a.next = now.Add(250 * time.Millisecond)
lease := &connectionLease{a: a, path: paths[index], epoch: a.epoch, stage: "turn", started: now}
a.probes[lease] = struct{}{}
a.mu.Unlock()
log.Printf("[CONNECTION] TRY %s", lease.path.kind())
return lease, nil
}
}
// Paused workers sleep on a notification, not repeating timers.
var wakeAt time.Time
if !a.blocked && !a.sleeping && !a.paused && a.pending < limit {
if now.Before(a.next) {
wakeAt = a.next
} else {
for _, path := range paths {
if a.noUDP && (path.kind() == "udp" || path.kind() == "h3") {
continue
}
expiry := a.excluded[path.key()]
if (path.kind() == "udp" || path.kind() == "h3") && a.udpRetryAfter.After(expiry) {
expiry = a.udpRetryAfter
}
if wakeAt.IsZero() || expiry.Before(wakeAt) {
wakeAt = expiry
}
}
}
}
changed := a.changed
a.mu.Unlock()
var timer *time.Timer
var tick <-chan time.Time
if !wakeAt.IsZero() {
timer = time.NewTimer(time.Until(wakeAt))
tick = timer.C
}
select {
case <-ctx.Done():
if timer != nil {
timer.Stop()
}
return nil, ctx.Err()
case <-changed:
if timer != nil {
timer.Stop()
}
case <-tick:
}
}
}
func (l *connectionLease) accept() bool {
a := l.a
a.mu.Lock()
defer a.mu.Unlock()
if l.interrupted || l.ready || l.finished || l.epoch != a.epoch {
return false
}
delete(a.probes, l)
l.ready = true
a.pending--
a.active++
if l.epoch == a.epoch {
a.readyPaths[l.path.key()]++
a.readyKinds[l.path.kind()]++
// A reserve worker does not disprove already working UDP workers.
if a.readyKinds["udp"] > 0 {
a.preferred = "udp"
} else {
a.preferred = l.path.kind()
}
if l.path.kind() == "udp" {
a.udpRetryAfter = time.Time{}
}
l.stage = "active"
a.failures = 0
a.paused = false
delete(a.excluded, l.path.key())
log.Printf("[CONNECTION] READY %d %s", a.epoch, l.path.kind())
}
a.notifyLocked()
return true
}
func connectionPathFailure(err error) bool {
if errors.Is(err, errUplinkPathReplacement) {
return false
}
if _, limited := workerPolicyLimit(err); limited {
return false
}
if isCredentialTURNError(err) || isTURNCapacityError(err) {
return false
}
if err != nil {
s := strings.ToUpper(err.Error())
for _, marker := range []string{"FATAL_AUTH", "FATAL_TRANSPORT", "CAPTCHA", "FLOOD", "CALL_FULL", "INVALID_JOIN_LINK"} {
if strings.Contains(s, marker) {
return false
}
}
}
return true
}
func (l *connectionLease) finish(err error, cancelled bool) {
a := l.a
a.mu.Lock()
defer a.mu.Unlock()
if l.finished {
return
}
l.finished = true
delete(a.probes, l)
if l.ready {
a.active--
if l.epoch == a.epoch {
a.readyPaths[l.path.key()]--
a.readyKinds[l.path.kind()]--
if a.readyKinds[a.preferred] == 0 {
for _, kind := range []string{"udp", "tls", "tls-front", "tcp", "h2", "h3"} {
if a.readyKinds[kind] > 0 {
a.preferred = kind
break
}
}
}
}
} else {
a.pending--
}
if l.epoch == a.epoch && !cancelled && !l.interrupted && !a.sleeping && !a.blocked {
if errors.Is(err, errUplinkPathReplacement) {
a.notifyLocked()
return
}
log.Printf("[CONNECTION] FAILED %d %s %s %s %d", a.epoch, l.path.kind(), l.stage, connectionFailureReason(err), time.Since(l.started).Milliseconds())
if connectionPathFailure(err) {
if l.path.kind() == "udp" || l.path.kind() == "h3" {
if a.readyKinds["udp"]+a.readyKinds["h3"] == 0 {
if !time.Now().Before(a.udpRetryAfter) {
a.udpRetryAfter = time.Now().Add(5 * time.Minute)
log.Printf("[CONNECTION] UDP_BACKOFF %d", a.epoch)
}
} else {
log.Printf("[CONNECTION] UDP_PARTIAL %d", a.epoch)
}
}
a.failures++
if a.readyPaths[l.path.key()] == 0 {
a.excluded[l.path.key()] = time.Now().Add(90 * time.Second)
}
if a.failures >= connectionAttemptBudget {
a.next = time.Now().Add(90 * time.Second)
}
} else {
a.failures++
// Authentication and admission control are not network evidence.
a.next = time.Now().Add(20 * time.Second)
}
}
a.notifyLocked()
}
func connectionFailureReason(err error) string {
if !connectionPathFailure(err) {
if _, limited := workerPolicyLimit(err); limited {
return "limit"
}
if isTURNCapacityError(err) {
return "capacity"
}
if err != nil && strings.Contains(err.Error(), "FATAL_TRANSPORT") {
return "protocol"
}
return "auth"
}
if err == nil {
return "closed"
}
lower := strings.ToLower(err.Error())
if errors.Is(err, context.DeadlineExceeded) || strings.Contains(lower, "timeout") || strings.Contains(lower, "deadline") {
return "timeout"
}
if errors.Is(err, context.Canceled) {
return "interrupted"
}
return "network"
}
// The established relay must carry traffic in both directions. This also
// works with old servers: keepalive is part of the original DTLS protocol.
func confirmConnectionPath(ctx context.Context, conn net.Conn) error {
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
stop := context.AfterFunc(ctx, func() { _ = conn.SetDeadline(time.Now()) })
defer stop()
defer conn.SetDeadline(time.Time{})
if _, err := conn.Write([]byte{keepaliveByte}); err != nil {
return err
}
buf := make([]byte, readBufSize)
for {
n, err := conn.Read(buf)
if err != nil {
return fmt.Errorf("проверка рабочего пути: %w", err)
}
if n == 1 && buf[0] == keepaliveByte {
return nil
}
// Data from already active workers may arrive before our ping reply.
}
}
+1
View File
@@ -63,6 +63,7 @@ func TestClassifyHashCheckErrorKeepsTerminalAndTransientStatusesSeparate(t *test
status string
}{
{errText: "INVALID_JOIN_LINK: VK API error_code:9008", status: "dead"},
{errText: "VK API error_code:9005 Call requires auth", status: "auth_required"},
{errText: "ANON_BLOCKED: anonymous join is disabled", status: "blocked"},
{errText: "CALL_FULL: call is full", status: "full"},
{errText: "vchat.joinConversationByLink: participant.check.flood", status: "limited"},
+166 -49
View File
@@ -42,8 +42,10 @@ func putPktBuf(b []byte) {
}
const (
returnChBuf = 384
deviceWakeHealthGrace = 60 * time.Second
returnChBuf = 384
deviceWakeHealthGrace = 60 * time.Second
uplinkBulkQueueCapacity = 512
uplinkBulkQueueMaxAge = 50 * time.Millisecond
// chunkSize — количество последовательных пакетов, отправляемых в один worker
// перед переключением на следующий.
@@ -56,8 +58,8 @@ const (
// С chunk=16 пакеты реже перескакивают между путями с разной задержкой. Это
// уменьшает reorder на активной многоканальной сессии, сохраняя равномерную
// загрузку всех workers.
// Reorder возможен только между chunk-границами, что покрывается WG replay
// window (2048 пакетов).
// Chunk не гарантирует порядок доставки: очереди и задержки путей различаются.
// Replay window отбрасывает старые повторы, но не восстанавливает порядок TCP.
//
// Все workers по-прежнему получают одинаковую долю трафика за полный цикл;
// фактический выигрыш зависит от различия задержек между TURN-путями.
@@ -65,6 +67,8 @@ const (
)
type WorkerSlot struct {
uplink *uplinkQuality
queue *transportQueue
ID int
SendCh chan []byte
WakeCh chan uint64
@@ -77,6 +81,15 @@ type WorkerSlot struct {
}
type Dispatcher struct {
workerAttempt atomic.Uint64
negotiatedTransport atomic.Uint32
uplinkBulk chan timedDatagram
uplinkIngress uplinkIngressMetrics
dispatchMu sync.Mutex
uplinkRecovery uplinkRecovery
uplinkPacing *uplinkPacer
downlinkOrder transportOrder
experiment string
localConn net.PacketConn
clientAddr atomic.Pointer[net.Addr]
workers atomic.Pointer[[]*WorkerSlot]
@@ -106,9 +119,14 @@ type Dispatcher struct {
wakeHealthGraceUntil atomic.Int64
}
func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats) *Dispatcher {
func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats, experiment ...string) *Dispatcher {
dctx, dcancel := context.WithCancel(ctx)
mode := experimentStandard
if len(experiment) != 0 {
mode = experiment[0]
}
d := &Dispatcher{
experiment: mode,
localConn: localConn,
ReturnCh: make(chan []byte, returnChBuf),
ctx: dctx,
@@ -117,18 +135,44 @@ func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats)
updateMetadataWaiters: make(map[string]*updateMetadataAssembly),
}
if mode == experimentUplink || mode == experimentAuto {
d.uplinkPacing = newUplinkPacer()
d.uplinkBulk = make(chan timedDatagram, uplinkBulkQueueCapacity)
d.wg.Add(2)
go func() { defer d.wg.Done(); d.uplinkPacing.run(dctx) }()
go d.runUplinkBulk()
}
empty := make([]*WorkerSlot, 0)
d.workers.Store(&empty)
d.wg.Add(2)
go d.readLoop()
go d.writeLoop()
if transportMetricsEnabled {
d.wg.Add(1)
go func() {
defer d.wg.Done()
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for {
select {
case <-d.ctx.Done():
return
case <-t.C:
d.downlinkOrder.report("client_downlink")
d.uplinkIngress.report(d.uplinkBulk)
}
}
}()
}
return d
}
func (d *Dispatcher) Shutdown() {
d.cancel()
d.wg.Wait()
d.downlinkOrder.report("client_downlink")
}
func (d *Dispatcher) Register(w *WorkerSlot) {
@@ -138,6 +182,9 @@ func (d *Dispatcher) Register(w *WorkerSlot) {
copy(newWorkers, *oldWorkers)
newWorkers[len(*oldWorkers)] = w
d.workers.Store(&newWorkers)
if w.uplink != nil && d.uplinkPacing != nil {
d.uplinkPacing.registerPath(w.uplink)
}
d.mu.Unlock()
log.Printf("[ДИСП] Воркер #%d зарегистрирован (всего: %d)", w.ID, len(newWorkers))
@@ -160,6 +207,9 @@ func (d *Dispatcher) Unregister(slot *WorkerSlot) {
}
}
d.workers.Store(&newWorkers)
if slot.uplink != nil && d.uplinkPacing != nil {
d.uplinkPacing.unregisterPath(slot.uplink)
}
d.mu.Unlock()
log.Printf("[ДИСП] Воркер #%d отключён (осталось: %d)", slot.ID, len(newWorkers))
if generation := d.wakeGeneration.Load(); generation > 0 && !d.deviceSleeping.Load() {
@@ -324,12 +374,13 @@ func (d *Dispatcher) claimStalledUserTraffic(now time.Time, timeout time.Duratio
//
// Логика: отправляем chunkSize подряд пакетов в один worker, потом переходим
// к следующему. Если текущий worker перегружен (канал полный) — немедленно
// ищем свободный worker и начинаем новый chunk на нём. Это гарантирует:
// - В рамках chunk пакеты идут через один TURN relay → in-order delivery
// - Между chunks — разные relay → максимальная агрегатная скорость
// - Нет блокировки, нет буферизации, нет дополнительного latency
// ищем свободный worker и начинаем новый chunk на нём. Порядок и пропускная
// способность зависят от потерь, очередей и задержек отдельных путей.
func (d *Dispatcher) readLoop() {
defer d.wg.Done()
if d.uplinkBulk != nil {
defer close(d.uplinkBulk)
}
for {
if err := d.ctx.Err(); err != nil {
@@ -352,57 +403,122 @@ func (d *Dispatcher) readLoop() {
d.clientAddr.Store(&addr)
d.stats.TotalBytesUp.Add(int64(n))
workersPtr := d.workers.Load()
if workersPtr == nil || len(*workersPtr) == 0 {
if d.usesUplink() && d.uplinkBulk != nil && n > 160 {
// Read and dispatch ACKs even while bulk pacing is waiting. Blocking
// this UDP reader would trap ACKs behind data in the socket buffer.
select {
case d.uplinkBulk <- timedDatagram{data: pkt, queued: time.Now()}:
if transportMetricsEnabled {
d.uplinkIngress.accepted.Add(1)
}
default:
if transportMetricsEnabled {
d.uplinkIngress.dropped.Add(1)
}
putPktBuf(pkt)
}
} else {
d.dispatchPacket(pkt)
}
}
}
func (d *Dispatcher) runUplinkBulk() {
defer d.wg.Done()
for queued := range d.uplinkBulk {
pkt := queued.data
// Absorb short local bursts without keeping a slow path's old bulk
// traffic queued indefinitely. ACKs still bypass this queue entirely.
if d.expireUplinkBulk(queued) {
continue
}
var started time.Time
if transportMetricsEnabled {
started = time.Now()
}
if d.uplinkPacing.wait(d.ctx, len(pkt)) != nil {
putPktBuf(pkt)
continue
}
if d.expireUplinkBulk(queued) {
continue
}
if transportMetricsEnabled {
d.uplinkIngress.pacingWait.observe(time.Since(started))
d.uplinkIngress.dispatched.Add(1)
}
d.dispatchPacket(pkt)
}
}
ws := *workersPtr
nw := len(ws)
wakeGeneration := d.wakeGeneration.Load()
deviceSleeping := d.deviceSleeping.Load()
func (d *Dispatcher) expireUplinkBulk(queued timedDatagram) bool {
if time.Since(queued.queued) <= uplinkBulkQueueMaxAge {
return false
}
if transportMetricsEnabled {
d.uplinkIngress.expired.Add(1)
}
putPktBuf(queued.data)
return true
}
sent := false
idx := d.rrIndex % nw
func (d *Dispatcher) dispatchPacket(pkt []byte) {
d.dispatchMu.Lock()
defer d.dispatchMu.Unlock()
n := len(pkt)
workersPtr := d.workers.Load()
if workersPtr == nil || len(*workersPtr) == 0 {
putPktBuf(pkt)
return
}
// After wake, a registered worker is only a candidate after its own
// current-generation keepalive has returned. This keeps stale sockets
// out of the user-data round robin while healthy workers keep carrying
// traffic and the remaining sessions reconnect independently.
for offset := 0; offset < nw; offset++ {
candidateIdx := (idx + offset) % nw
candidate := ws[candidateIdx]
if !workerEligibleForWakeGeneration(candidate, wakeGeneration, deviceSleeping) {
continue
ws := *workersPtr
nw := len(ws)
wakeGeneration := d.wakeGeneration.Load()
deviceSleeping := d.deviceSleeping.Load()
if d.usesUplink() {
ensureUplinkServiceFloor(ws, wakeGeneration, deviceSleeping)
}
sent := false
idx := d.rrIndex % nw
// After wake, a registered worker is only a candidate after its own
// current-generation keepalive has returned. This keeps stale sockets
// out of the user-data round robin while healthy workers keep carrying
// traffic and the remaining sessions reconnect independently.
for offset := 0; offset < nw; offset++ {
candidateIdx := (idx + offset) % nw
candidate := ws[candidateIdx]
if !workerEligibleForWakeGeneration(candidate, wakeGeneration, deviceSleeping) || (n > 160 && candidate.uplink != nil && candidate.uplink.muted.Load()) {
continue
}
if candidate.offerData(pkt) {
sent = true
if offset == 0 {
d.rrCount++
} else {
d.rrIndex = candidateIdx
d.rrCount = 1
}
select {
case candidate.SendCh <- pkt:
sent = true
if offset == 0 {
d.rrCount++
} else {
d.rrIndex = candidateIdx
d.rrCount = 1
}
if d.rrCount >= chunkSize {
d.rrIndex = (candidateIdx + 1) % nw
d.rrCount = 0
}
default:
}
if sent {
break
rotate := d.rrCount >= chunkSize
if rotate {
d.rrIndex = (candidateIdx + 1) % nw
d.rrCount = 0
}
}
if !sent {
// Все workers перегружены — сдвигаем указатель, пакет дропается
d.rrIndex = (idx + 1) % nw
d.rrCount = 0
putPktBuf(pkt)
if sent {
break
}
}
if !sent {
// Все workers перегружены — сдвигаем указатель, пакет дропается
d.rrIndex = (idx + 1) % nw
d.rrCount = 0
putPktBuf(pkt)
}
}
func (d *Dispatcher) writeLoop() {
@@ -413,6 +529,7 @@ func (d *Dispatcher) writeLoop() {
case <-d.ctx.Done():
return
case pkt := <-d.ReturnCh:
d.downlinkOrder.observe(pkt)
addrPtr := d.clientAddr.Load()
if addrPtr == nil {
putPktBuf(pkt)
+4
View File
@@ -3,6 +3,7 @@ module wg-turn-client
go 1.26
require (
wdtt.local/pathprobe v0.0.0
github.com/Diniboy1123/connect-ip-go v0.0.0-20260613064811-66cba32d7d33
github.com/bogdanfinn/fhttp v0.6.8
github.com/bogdanfinn/tls-client v1.15.1
@@ -18,6 +19,7 @@ require (
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446
)
require (
github.com/andybalholm/brotli v1.2.0 // indirect
github.com/bdandy/go-errors v1.2.2 // indirect
@@ -40,3 +42,5 @@ require (
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect
)
replace wdtt.local/pathprobe => ../pathprobe
+28 -2
View File
@@ -474,6 +474,11 @@ func WorkerGroup(
}
}
if tp.Auto != nil {
if err := configStartGate.wait(ctx, getConfig); err != nil {
return
}
}
hashCandidates := workerHashCandidates(tp.Hashes, hashIndex, requestedWorkers, hashFallback)
selectedHash := 0
hash := hashCandidates[selectedHash]
@@ -481,6 +486,11 @@ func WorkerGroup(
credStreamID := groupID * 100
fetchCredentials := func(candidateHash string) credentialFetchResult {
if tp.Auto != nil {
if err := tp.Auto.waitAvailable(ctx); err != nil {
return credentialFetchResult{err: err}
}
}
return credentialRequests.fetch(ctx, func() (string, string, []string, error) {
return GetCreds(ctx, candidateHash, credStreamID)
})
@@ -688,6 +698,12 @@ func WorkerGroup(
if ctx.Err() != nil {
return
}
if errors.Is(sessErr, errUplinkPathReplacement) {
// Local delivery failure does not invalidate VK credentials.
// The dispatcher has already granted a bounded recovery permit.
turnCandidateRetry++
continue
}
relayHandshakeFailed := shouldRotateTurnCandidateAfterSessionError(sessErr)
if relayHandshakeFailed {
turnCandidateRetry++
@@ -729,8 +745,14 @@ func WorkerGroup(
}
if strings.Contains(errStr, "хеш мёртв") ||
strings.Contains(errStr, "FATAL_AUTH") {
strings.Contains(errStr, "FATAL_AUTH") || strings.Contains(errStr, "FATAL_TRANSPORT") {
log.Printf("[ВОРКЕР #%d] Фатальная ошибка: %s", wid, errStr)
if strings.Contains(errStr, "FATAL_TRANSPORT") {
// Other groups may still be waiting for this group's
// configuration. An unsupported mode cannot recover by
// retrying workers, even without an Android log reader.
cancel()
}
return
}
@@ -742,6 +764,7 @@ func WorkerGroup(
log.Printf("[ВОРКЕР #%d] [TURN] Ошибка allocation/кредов, обновляем TURN-креды и повторяем (попытка %d): %s", wid, attempt, errStr)
refreshResult = refreshCreds("TURN allocation error", credsRevision)
} else if turnCapacityLimited {
d.uplinkRecovery.capacityLimited(time.Now())
startedRound, round, waitErr := turnCapacityGate.wait(ctx, wid)
if startedRound {
log.Printf("[ВОРКЕР #%d] [TURN] Узел временно ограничил новые allocation; снижаем темп повторов (раунд %d), креды сохранены: %s", wid, round, errStr)
@@ -750,7 +773,7 @@ func WorkerGroup(
return
}
continue
} else if relayHandshakeFailed &&
} else if tp.Auto == nil && relayHandshakeFailed &&
hashFallback &&
len(credsSnapshot.TurnURLs) > 0 &&
turnCandidateRetry%len(credsSnapshot.TurnURLs) == 0 {
@@ -894,6 +917,9 @@ func normalizeVKJoinHash(input string) string {
// TurnParams — конфигурация TURN
type TurnParams struct {
Auto *connectionPolicy
NoUDP bool
Experiment string
Host string
Port string
Hashes []string
+62 -39
View File
@@ -142,6 +142,8 @@ func classifyHashCheckError(err error) (string, string) {
}
text := strings.ToLower(err.Error())
switch {
case strings.Contains(text, "error_code:9005") || strings.Contains(text, "call requires auth"):
return "auth_required", "Звонок требует входа в ВК и не подходит для подключения"
case strings.Contains(text, "captcha_required") || strings.Contains(text, "captcha_wait_required"):
return "captcha", "VK просит капчу"
case strings.Contains(text, "invalid_join_link") ||
@@ -267,21 +269,7 @@ func main() {
// Сигналы
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
go func() {
select {
case s := <-sig:
log.Printf("[КЛИЕНТ] Сигнал %v, завершаю...", s)
cancel()
case <-ctx.Done():
return
}
select {
case s := <-sig:
log.Printf("[КЛИЕНТ] Повторный %v, принудительный выход", s)
os.Exit(1)
case <-ctx.Done():
}
}()
go runNativeShutdownGuard(ctx, cancel, sig, os.Exit, 1250*time.Millisecond)
var pauseFlag int32
var activeDispatcher atomic.Pointer[Dispatcher]
@@ -289,6 +277,8 @@ func main() {
deviceSleeping := false
startupConfigCh := make(chan nativeStartupConfigResult, 1)
var connectionController atomic.Pointer[connectionPolicy]
connectionController.Store(newConnectionPolicy("", false))
// STDIN для конфигурации запуска, PAUSE/RESUME/STOP и CAPTCHA_RESULT.
// Секреты запуска не передаются через argv/environment, где их может
// прочитать системная диагностика Android.
@@ -297,7 +287,11 @@ func main() {
scanner.Buffer(make([]byte, 4096), 48*1024)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if controller := connectionController.Load(); controller != nil {
controller.command(line)
}
switch {
case line == "CONNECTION_NETWORK" || line == "CONNECTION_OFFLINE" || line == "CONNECTION_ONLINE":
case strings.HasPrefix(line, startupConfigPrefix):
secrets, err := decodeNativeStartupSecrets(strings.TrimPrefix(line, startupConfigPrefix))
select {
@@ -428,16 +422,19 @@ func main() {
"использовать остальные VK-хеши как резерв групп",
)
experiment := flag.String("transport-experiment", experimentAuto, "transport compatibility: auto|standard|uplink")
metrics := flag.Bool("transport-metrics", false, "обезличенные метрики очередей и порядка пакетов")
deviceID := flag.String("device-id", "unknown", "уникальный ID устройства")
deviceInfo := flag.String("device-info", "", "JSON с безопасной информацией об устройстве")
transportSessionFlag := flag.String("transport-session", "", "поколение текущего запуска транспорта")
connPassword := flag.String("password", "", "пароль подключения")
captchaMode := flag.String("captcha-mode", "auto", "режим обхода капчи (auto/wv/rjs)")
vkCallsPreflight := flag.Bool("vkcalls-preflight", true, "пробовать VKCalls до captcha-цепочки")
connectionUDPBackoff := flag.Int("connection-udp-backoff", 0, "пауза после недавнего отказа UDP, секунды")
turnStreamFirst := flag.Bool(
"turn-stream-first",
false,
"сначала пробовать TURN/TLS и TURN/TCP, сохраняя UDP как резерв",
"использовать только TURN/TLS, TURN/TCP и MASQUE HTTP/2",
)
turnSNI := flag.String(
"turn-sni",
@@ -447,7 +444,7 @@ func main() {
rtMasque := flag.Bool(
"rt-masque",
false,
"после прямых путей Сети РТ пробовать WARP CONNECT-IP по HTTP/2 и HTTP/3",
"резерв WARP CONNECT-IP по разрешённым протоколам HTTP/2 и HTTP/3",
)
rtMasqueConfig := flag.String(
"rt-masque-config",
@@ -483,6 +480,7 @@ func main() {
proxyAllowedCIDR := flag.String("proxy-allow-cidr", "", "разрешённая подсеть клиента для LAN-прокси")
flag.Parse()
transportMetricsEnabled = *metrics
var startupSecrets nativeStartupSecrets
if *startupConfigStdin {
select {
@@ -530,21 +528,17 @@ func main() {
}
activeCaptchaMode := setCaptchaMode(*captchaMode)
setVKCallsPreflight(*vkCallsPreflight)
var normalizedTurnSNI string
if *turnStreamFirst {
var turnSNIErr error
normalizedTurnSNI, turnSNIErr = normalizeTURNFrontSNI(*turnSNI)
if turnSNIErr != nil {
log.Fatalf("[КЛИЕНТ] Некорректный TURN SNI: %v", turnSNIErr)
}
if normalizedTurnSNI != "" {
log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом; внешний TLS SNI=%s", normalizedTurnSNI)
} else {
log.Printf("[TURN] Режим «Сеть РТ»: TURN/TLS, затем TCP ко всем адресам VK с разделением первого STUN-запроса; UDP остаётся резервом")
}
normalizedTurnSNI, turnSNIErr := normalizeTURNFrontSNI(*turnSNI)
if turnSNIErr != nil {
log.Fatalf("[КЛИЕНТ] Некорректный TURN SNI: %v", turnSNIErr)
}
if *rtMasque && !*turnStreamFirst {
log.Printf("[MASQUE] Проигнорирован: механизм доступен только вместе с режимом «Сеть РТ»")
mode := "UDP: сначала UDP, при недоступности — TCP/TLS"
if *turnStreamFirst {
mode = "TCP/TLS: внешний UDP и HTTP/3 запрещены"
}
log.Printf("[ПОДКЛЮЧЕНИЕ] %s", mode)
if normalizedTurnSNI != "" {
log.Printf("[TURN] Внешний TLS SNI=%s", normalizedTurnSNI)
}
if *vkHash == "" {
@@ -618,26 +612,35 @@ func main() {
*numW = workersPerGroup
}
*numW = (*numW / workersPerGroup) * workersPerGroup
useConfigFirstStart := *configFirstStart
useConfigFirstStart := true // Both connection modes verify the server before adding workers.
_ = configFirstStart // Retained CLI option for callers using the existing startup contract.
useHashFallback := *hashFallback
var masqueManager *warpMasqueManager
if *turnStreamFirst && *rtMasque {
if *rtMasque {
if err := configureWarpAPIRelay(*warpAPIRelay); err != nil {
log.Printf("[MASQUE] Локальный выход для регистрации WARP отклонён: %v; продолжаем прямые попытки", err)
}
masqueManager, err = newWarpMasqueManager(ctx, *rtMasqueConfig, normalizedTurnSNI, *rtMasqueAcceptTOS)
if err != nil {
log.Printf("[MASQUE] Не удалось включить новый механизм: %v; прямые пути «Сети РТ» остаются доступны", err)
log.Printf("[MASQUE] Не удалось подготовить резерв: %v; подключение без MASQUE остаётся доступно", err)
masqueManager = nil
} else {
defer masqueManager.Close()
log.Printf("[MASQUE] Включён резерв после прямых путей: HTTP/2 (TCP/443), затем HTTP/3 (QUIC/443)")
go masqueManager.prewarmConfig()
masqueManager.singleEnrollment = true
if *turnStreamFirst {
log.Print("[MASQUE] Включён резерв: только HTTP/2 (TCP/443); HTTP/3 запрещён режимом TCP/TLS")
} else {
log.Print("[MASQUE] Включён резерв: доступны HTTP/2 (TCP/443) и HTTP/3 (QUIC/443)")
}
}
}
if err := validateTransportExperiment(*experiment); err != nil {
log.Fatal(err)
}
tp := &TurnParams{
Experiment: *experiment,
Host: *host,
Port: *port,
Hashes: hashes,
@@ -646,10 +649,25 @@ func main() {
WrapKey: wrapKey,
}
tp.NoUDP = *turnStreamFirst
{
tp.Auto = connectionController.Load()
tp.Auto.configure("", *turnStreamFirst)
tp.Auto.deferUDP(time.Duration(max(0, min(300, *connectionUDPBackoff))) * time.Second)
transportLifecycleMu.Lock()
if deviceSleeping {
tp.Auto.command("DEVICE_SLEEP")
}
if atomic.LoadInt32(&pauseFlag) != 0 {
tp.Auto.command("PAUSE")
}
connectionController.Store(tp.Auto)
transportLifecycleMu.Unlock()
}
// Слушаем локально с ожиданием (если старый процесс еще не убит Parent Watcher'ом)
var localConn net.PacketConn
actualListenAddr := *listen
for i := 0; i < 5; i++ {
for i := 0; localConn == nil && i < 5; i++ {
localConn, err = net.ListenPacket("udp", actualListenAddr)
if err == nil {
break
@@ -714,7 +732,7 @@ func main() {
}()
go stats.RunLoop(shutdownCh)
disp := NewDispatcher(ctx, localConn, stats)
disp := NewDispatcher(ctx, localConn, stats, *experiment)
disp.setUnansweredUserTrafficHealthEnabled(normalizedClientMode == "vpn")
transportLifecycleMu.Lock()
activeDispatcher.Store(disp)
@@ -787,7 +805,12 @@ func main() {
},
)
if err != nil && ctx.Err() == nil {
log.Printf("PROXY_ERROR|%v", err)
if address, portInUse := proxyPortInUseAddress(err); portInUse {
log.Printf("[ПРОКСИ] Порт занят: %s", address)
log.Printf("PROXY_ERROR|port_in_use|%s", address)
} else {
log.Printf("PROXY_ERROR|startup|%v", err)
}
cancel()
}
return
+12 -6
View File
@@ -2,7 +2,7 @@ package main
// The Cloudflare WARP MASQUE interoperability in this file is adapted from
// Diniboy1123/usque (MIT, commit 6aa03fc97d12848dce34eedbd187fb1077b5d1ea).
// It is intentionally isolated behind the explicit Android «Сеть РТ» +
// It is intentionally isolated behind the explicit Android «Авто»/«TCP/TLS» +
// «MASQUE» opt-in. The ordinary WDTT transport never constructs this manager.
import (
@@ -70,7 +70,7 @@ var (
// warpAPIFragmentConn divides only the first TLS ClientHello write. It leaves
// DNS, addresses, certificate validation and all later HTTPS bytes untouched.
// The wrapper is used only after a normal WARP API TLS handshake times out and
// only while the explicit Android «Сеть РТ» + «MASQUE» mode is enrolling.
// only while the explicit Android «Авто»/«TCP/TLS» + «MASQUE» mode is enrolling.
type warpAPIFragmentConn struct {
net.Conn
mu sync.Mutex
@@ -1224,10 +1224,12 @@ func (transport *warpMasqueTransport) DialContext(ctx context.Context, target st
}
type warpMasqueManager struct {
ctx context.Context
path string
sni string
acceptTOS bool
singleEnrollment bool
enrollmentAttempted bool
ctx context.Context
path string
sni string
acceptTOS bool
mu sync.Mutex
config *warpMasqueConfig
@@ -1284,6 +1286,10 @@ func (manager *warpMasqueManager) ensureConfigLocked() (*warpMasqueConfig, error
if !manager.acceptTOS {
return nil, errors.New("для первой регистрации WARP требуется согласие с условиями Cloudflare")
}
if manager.singleEnrollment && manager.enrollmentAttempted {
return nil, errors.New("регистрация WARP уже запрашивалась; повтор только после нового подключения")
}
manager.enrollmentAttempted = true
logMasque("регистрация начата: этап 1/4 — создаём отдельное устройство WARP в Cloudflare")
enrollCtx, cancel := context.WithTimeout(manager.ctx, 40*time.Second)
defer cancel()
+10 -1
View File
@@ -102,6 +102,10 @@ func obfsBuildNonce(ssrc uint32, seq uint16, ts uint32) []byte {
//
// [V=2,P=1,X=0,CC=0 | PT | SeqNum | Timestamp | SSRC | encrypted_payload | padding | padLen]
func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]byte, error) {
return obfsWrapPacketInto(nil, key, payload, cfg, state)
}
func obfsWrapPacketInto(dst, key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]byte, error) {
if len(key) != wrapKeyLen {
return nil, fmt.Errorf("obfs: key must be %d bytes (got %d)", wrapKeyLen, len(key))
}
@@ -131,7 +135,12 @@ func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]b
// Allocate output: 12 (header) + payload + AEAD tag + padTotal
outLen := 12 + len(payload) + chacha20poly1305.Overhead + padTotal
out := make([]byte, outLen)
var out []byte
if cap(dst) >= outLen {
out = dst[:outLen]
} else {
out = make([]byte, outLen)
}
// RTP Header (12 bytes)
out[0] = 0x80 | 0x20 // V=2, P=1 (padding present)
+5
View File
@@ -8,6 +8,7 @@ import (
"strconv"
"strings"
"time"
"wdtt.local/pathprobe"
)
type workerPolicyLimitError struct {
@@ -65,6 +66,7 @@ func RequestConfig(
ctx context.Context,
conn net.Conn,
localPort, deviceID, password, deviceInfo, transportSession string,
worker ...pathprobe.Worker,
) (string, error) {
payload := fmt.Sprintf("GETCONF:%s|%s|%s", localPort, deviceID, password)
safeDeviceInfo := strings.ReplaceAll(strings.TrimSpace(deviceInfo), "|", " ")
@@ -74,6 +76,9 @@ func RequestConfig(
}
if safeTransportSession != "" {
payload += "|" + safeTransportSession
if len(worker) > 0 && worker[0].Valid() {
payload += "|" + worker[0].String()
}
}
if _, err := conn.Write([]byte(payload)); err != nil {
return "", fmt.Errorf("отправка GETCONF: %w", err)
+26 -1
View File
@@ -10,6 +10,7 @@ import (
"net/netip"
"strings"
"sync"
"syscall"
"time"
)
@@ -20,6 +21,30 @@ type proxyListener struct {
access proxyAccessPolicy
}
type proxyListenError struct {
Address string
Err error
}
func (err *proxyListenError) Error() string {
return fmt.Sprintf("прокси не смог занять %s: %v", err.Address, err.Err)
}
func (err *proxyListenError) Unwrap() error {
return err.Err
}
func proxyPortInUseAddress(err error) (string, bool) {
if !errors.Is(err, syscall.EADDRINUSE) {
return "", false
}
var listenErr *proxyListenError
if !errors.As(err, &listenErr) || listenErr.Address == "" {
return "", false
}
return listenErr.Address, true
}
type bufferedProxyConn struct {
net.Conn
reader io.Reader
@@ -106,7 +131,7 @@ func runUnifiedProxyServer(
for _, opened := range listeners {
_ = opened.listener.Close()
}
return fmt.Errorf("прокси не смог занять %s: %w", address, listenErr)
return &proxyListenError{Address: address, Err: listenErr}
}
listeners = append(listeners, proxyListener{listener: listener, access: policies[index]})
}
+117
View File
@@ -60,6 +60,123 @@ func TestValidateProxyListenAddressesRejectsUnsafeCombinations(t *testing.T) {
}
}
func TestUnifiedProxyReportsFirstListenerPortInUse(t *testing.T) {
occupied, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer occupied.Close()
err = runUnifiedProxyServer(
context.Background(),
"auto",
[]string{occupied.Addr().String()},
systemSocksDialer{},
false,
"",
"",
true,
"",
nil,
)
address, portInUse := proxyPortInUseAddress(err)
if !portInUse || address != occupied.Addr().String() {
t.Fatalf("port conflict = %q, %t; error=%v", address, portInUse, err)
}
}
func TestUnifiedProxyClosesFirstListenerWhenSecondPortIsInUse(t *testing.T) {
portSource, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
_, port, err := net.SplitHostPort(portSource.Addr().String())
if err != nil {
t.Fatal(err)
}
_ = portSource.Close()
firstAddress := net.JoinHostPort("127.0.0.1", port)
secondAddress := net.JoinHostPort("127.0.0.2", port)
occupiedSecond, err := net.Listen("tcp4", secondAddress)
if err != nil {
t.Skipf("second loopback address is unavailable: %v", err)
}
defer occupiedSecond.Close()
err = runUnifiedProxyServer(
context.Background(),
"socks5",
[]string{firstAddress, secondAddress},
systemSocksDialer{},
false,
"",
"",
true,
"",
nil,
)
address, portInUse := proxyPortInUseAddress(err)
if !portInUse || address != secondAddress {
t.Fatalf("second conflict = %q, %t; error=%v", address, portInUse, err)
}
reopenedFirst, err := net.Listen("tcp4", firstAddress)
if err != nil {
t.Fatalf("first listener remained open after transactional failure: %v", err)
}
_ = reopenedFirst.Close()
}
func TestUnifiedProxyReadyForEveryMode(t *testing.T) {
for _, mode := range []string{"socks5", "http", "auto"} {
t.Run(mode, func(t *testing.T) {
reserved, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
listenAddress := reserved.Addr().String()
_ = reserved.Close()
ctx, cancel := context.WithCancel(context.Background())
ready := make(chan []string, 1)
done := make(chan error, 1)
go func() {
done <- runUnifiedProxyServer(
ctx,
mode,
[]string{listenAddress},
systemSocksDialer{},
false,
"",
"",
true,
"",
func(addresses []string) { ready <- addresses },
)
}()
select {
case addresses := <-ready:
if len(addresses) != 1 || addresses[0] != listenAddress {
t.Fatalf("ready addresses=%v", addresses)
}
case err := <-done:
t.Fatalf("proxy failed before ready: %v", err)
case <-time.After(2 * time.Second):
t.Fatal("proxy did not become ready")
}
cancel()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(2 * time.Second):
t.Fatal("proxy did not stop")
}
})
}
}
func TestAutoProxyDetectsSOCKSAndHTTPWithoutWaitingForMoreData(t *testing.T) {
for name, greeting := range map[string][]byte{
"SOCKS5": {socksVersion5},
+266 -96
View File
@@ -14,6 +14,8 @@ import (
"sync/atomic"
"time"
"wdtt.local/pathprobe"
"github.com/cbeuw/connutil"
"github.com/pion/dtls/v3"
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
@@ -199,7 +201,7 @@ func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { return c
// splitFirstWriteConn fragments the first STUN request so its magic cookie
// crosses TCP segment boundaries. Some shallow DPI rules classify plain TURN
// by looking only at the first segment. This wrapper is enabled exclusively by
// the explicit «Сеть РТ» mode; ordinary operators keep the original writes.
// stream-first connection modes; ordinary mode keeps the original writes.
type splitFirstWriteConn struct {
net.Conn
splitAt int
@@ -264,7 +266,7 @@ func normalizeTURNFrontSNI(value string) (string, error) {
return host, nil
}
func verifyTURNCertificateChainWithoutHostname(state tls.ConnectionState) error {
func verifyTURNPeerCertificate(state tls.ConnectionState, hostname string, roots *x509.CertPool) error {
if len(state.PeerCertificates) == 0 {
return fmt.Errorf("TURN TLS не прислал сертификат")
}
@@ -274,6 +276,8 @@ func verifyTURNCertificateChainWithoutHostname(state tls.ConnectionState) error
}
_, err := state.PeerCertificates[0].Verify(x509.VerifyOptions{
Intermediates: intermediates,
Roots: roots,
DNSName: hostname,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
})
if err != nil {
@@ -293,11 +297,13 @@ func turnTLSConfig(endpoint turnEndpoint, frontSNI string) *tls.Config {
}
// При подмене SNI имя сертификата ожидаемо относится к TURN-узлу, а не к
// домену белого списка. Отключаем только сопоставление имени: публичная CA-
// цепочка всё равно проверяется в VerifyConnection.
// домену белого списка. VerifyConnection проверяет цепочку И настоящее
// имя TURN-узла из реквизитов; frontSNI не является доверенной личностью.
if frontSNI != "" && !strings.EqualFold(frontSNI, endpoint.Host) {
config.InsecureSkipVerify = true // проверка перенесена в VerifyConnection
config.VerifyConnection = verifyTURNCertificateChainWithoutHostname
config.VerifyConnection = func(state tls.ConnectionState) error {
return verifyTURNPeerCertificate(state, endpoint.Host, nil)
}
}
return config
}
@@ -332,14 +338,12 @@ func openTURNAllocation(
var turnConn net.PacketConn
switch endpoint.Transport {
case turnTransportUDP:
resolved, err := net.ResolveUDPAddr("udp", turnAddr)
if err != nil {
return nil, nil, fmt.Errorf("TURN UDP резолв %s: %w", turnAddr, err)
}
c, err := net.DialUDP("udp", nil, resolved)
dialer := &net.Dialer{Timeout: 6 * time.Second}
raw, err := dialer.DialContext(ctx, "udp", turnAddr)
if err != nil {
return nil, nil, fmt.Errorf("TURN UDP подключение %s: %w", turnAddr, err)
}
c := raw.(*net.UDPConn)
_ = c.SetReadBuffer(socketBufSize)
_ = c.SetWriteBuffer(socketBufSize)
turnConn = &connectedUDPConn{c}
@@ -372,6 +376,8 @@ func openTURNAllocation(
return nil, nil, fmt.Errorf("неподдерживаемый TURN transport: %s", endpoint.Transport)
}
stop := context.AfterFunc(ctx, func() { _ = turnConn.Close() })
defer stop()
return allocateTURNOnConn(endpoint, peer, creds, turnConn)
}
@@ -381,6 +387,14 @@ func allocateTURNOnConn(
creds *Credentials,
turnConn net.PacketConn,
) (*turn.Client, net.PacketConn, error) {
deletion := &turnDeletionTransport{PacketConn: turnConn, ack: make(chan struct{})}
turnConn = deletion
owned := false
defer func() {
if !owned {
_ = turnConn.Close()
}
}()
turnAddr := endpoint.address()
// RequestedAddressFamily
@@ -401,7 +415,6 @@ func allocateTURNOnConn(
LoggerFactory: &NullLoggerFactory{},
})
if err != nil {
_ = turnConn.Close()
return nil, nil, fmt.Errorf("TURN %s клиент %s: %w", endpoint.label(), turnAddr, err)
}
@@ -424,7 +437,8 @@ func allocateTURNOnConn(
return nil, nil, fmt.Errorf("TURN %s Allocate %s: %w", endpoint.label(), turnAddr, err)
}
return tc, relay, nil
owned = true
return tc, &ownedTURNAllocation{PacketConn: relay, transport: turnConn, closeClient: tc.Close, deletion: deletion}, nil
}
func openTURNAllocationOverMasque(
@@ -456,6 +470,8 @@ func openTURNAllocationOverMasque(
conn = tlsConn
}
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
defer stop()
return allocateTURNOnConn(endpoint, peer, creds, turn.NewSTUNConn(conn))
}
@@ -516,8 +532,11 @@ func RunSession(
preferTURNStream bool,
turnCandidateRetry int,
onTURNAllocated func(),
) (bool, error) {
) (delivered bool, sessionErr error) {
replacingUplink, recoveryComplete := d.uplinkRecovery.completion(sessionID)
defer recoveryComplete()
configDelivered := false
useWrap := len(tp.WrapKey) == wrapKeyLen
if len(creds.TurnURLs) == 0 {
return false, fmt.Errorf("нет TURN URL в учетных данных")
@@ -532,6 +551,45 @@ func RunSession(
if len(candidates) == 0 {
return false, fmt.Errorf("нет пригодных TURN URL в учетных данных")
}
var autoLease *connectionLease
var startupTimer *time.Timer
if tp.Auto != nil {
outerCtx := ctx
var acquireErr error
autoLease, acquireErr = tp.Auto.acquire(ctx, connectionPaths(candidates, tp, tp.NoUDP))
if acquireErr != nil {
return false, acquireErr
}
defer func() {
failure := sessionErr
if errors.Is(context.Cause(ctx), context.DeadlineExceeded) {
failure = context.DeadlineExceeded
}
autoLease.finish(failure, outerCtx.Err() != nil)
}()
var cancelCause context.CancelCauseFunc
ctx, cancelCause = context.WithCancelCause(ctx)
attemptCancel := func() { cancelCause(context.Canceled) }
autoLease.bind(attemptCancel)
defer attemptCancel()
// Includes Allocate, relay handshake and authenticated registration.
budget := 30 * time.Second
if autoLease.path.masque != "" {
budget = 60 * time.Second
}
startupTimer = time.AfterFunc(budget, func() { cancelCause(context.DeadlineExceeded) })
defer startupTimer.Stop()
candidates = []turnEndpoint{autoLease.path.endpoint}
}
if tp.NoUDP {
filtered := candidates[:0]
for _, c := range candidates {
if c.Transport != turnTransportUDP {
filtered = append(filtered, c)
}
}
candidates = filtered
}
directCandidates, masqueCandidates, finalUDPCandidates := turnCandidateStages(candidates, tp.Masque != nil)
var tc *turn.Client
@@ -540,51 +598,29 @@ func RunSession(
var selectedMasqueProtocol warpMasqueProtocol
var lastTURNErr error
var err error
for idx, candidate := range directCandidates {
if !preferTURNStream && idx == 0 {
log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address())
} else if !preferTURNStream {
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
} else if idx == 0 {
log.Printf("[СЕССИЯ #%d] [TURN] Путь %s (%s), %s", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream))
if autoLease != nil {
p := autoLease.path
if p.masque != "" {
tc, relay, err = openTURNAllocationOverMasque(ctx, p.endpoint, peer, creds, tp.Masque, p.masque)
} else {
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s), %s, после ошибки: %v", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream), lastTURNErr)
tc, relay, err = openTURNAllocation(ctx, p.endpoint, peer, creds, sessionID, p.front, true)
}
tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream)
if err == nil {
selectedEndpoint = candidate
break
}
lastTURNErr = err
if isCredentialTURNError(err) {
if err != nil {
return false, err
}
}
if relay == nil && tp.Masque != nil {
log.Printf("[СЕССИЯ #%d] [MASQUE] Прямые TCP/TLS-пути «Сети РТ» не сработали; до UDP пробуем WARP CONNECT-IP: %v", sessionID, lastTURNErr)
masqueProtocols:
for _, protocol := range tp.Masque.protocolOrder() {
for _, candidate := range masqueCandidates {
log.Printf("[СЕССИЯ #%d] [MASQUE] Пробуем TURN %s (%s) внутри CONNECT-IP %s", sessionID, candidate.label(), candidate.address(), protocol)
tc, relay, err = openTURNAllocationOverMasque(ctx, candidate, peer, creds, tp.Masque, protocol)
if err == nil {
selectedEndpoint = candidate
selectedMasqueProtocol = protocol
tp.Masque.markPreferred(protocol)
break masqueProtocols
}
lastTURNErr = err
log.Printf("[СЕССИЯ #%d] [MASQUE] %s через %s не сработал: %v", sessionID, candidate.label(), protocol, err)
if isCredentialTURNError(err) {
return false, err
}
selectedEndpoint, selectedMasqueProtocol = p.endpoint, p.masque
} else {
for idx, candidate := range directCandidates {
if !preferTURNStream && idx == 0 {
log.Printf("[СЕССИЯ #%d] TURN %s (%s)", sessionID, candidate.label(), candidate.address())
} else if !preferTURNStream {
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s) после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
} else if idx == 0 {
log.Printf("[СЕССИЯ #%d] [TURN] Путь %s (%s), %s", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream))
} else {
log.Printf("[СЕССИЯ #%d] [TURN] Резервный путь %s (%s), %s, после ошибки: %v", sessionID, candidate.label(), candidate.address(), turnPathSNI(candidate, tp.TLSFrontSNI, preferTURNStream), lastTURNErr)
}
}
}
if relay == nil && tp.Masque != nil {
for _, candidate := range finalUDPCandidates {
log.Printf("[СЕССИЯ #%d] [TURN] Последний резерв после MASQUE: %s (%s), после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream)
if err == nil {
selectedEndpoint = candidate
@@ -595,11 +631,51 @@ func RunSession(
return false, err
}
}
if relay == nil && tp.Masque != nil {
log.Printf("[СЕССИЯ #%d] [MASQUE] Прямые TCP/TLS-пути не сработали; пробуем резерв MASQUE: %v", sessionID, lastTURNErr)
masqueProtocols:
for _, protocol := range tp.Masque.protocolOrder() {
if tp.NoUDP && protocol == warpMasqueHTTP3 {
continue
}
for _, candidate := range masqueCandidates {
log.Printf("[СЕССИЯ #%d] [MASQUE] Пробуем TURN %s (%s) внутри CONNECT-IP %s", sessionID, candidate.label(), candidate.address(), protocol)
tc, relay, err = openTURNAllocationOverMasque(ctx, candidate, peer, creds, tp.Masque, protocol)
if err == nil {
selectedEndpoint = candidate
selectedMasqueProtocol = protocol
tp.Masque.markPreferred(protocol)
break masqueProtocols
}
lastTURNErr = err
log.Printf("[СЕССИЯ #%d] [MASQUE] %s через %s не сработал: %v", sessionID, candidate.label(), protocol, err)
if isCredentialTURNError(err) {
return false, err
}
}
}
}
if relay == nil && tp.Masque != nil {
for _, candidate := range finalUDPCandidates {
log.Printf("[СЕССИЯ #%d] [TURN] Последний резерв после MASQUE: %s (%s), после ошибки: %v", sessionID, candidate.label(), candidate.address(), lastTURNErr)
tc, relay, err = openTURNAllocation(ctx, candidate, peer, creds, sessionID, tp.TLSFrontSNI, preferTURNStream)
if err == nil {
selectedEndpoint = candidate
break
}
lastTURNErr = err
if isCredentialTURNError(err) {
return false, err
}
}
}
}
if relay == nil && lastTURNErr == nil {
return false, fmt.Errorf("нет разрешённых путей подключения")
}
if lastTURNErr != nil && relay == nil {
return false, lastTURNErr
}
defer tc.Close()
defer relay.Close()
// Reset error count on successful allocation
@@ -640,8 +716,6 @@ func RunSession(
var relayWg sync.WaitGroup
relayWg.Add(2)
useWrap := len(tp.WrapKey) == wrapKeyLen
// Initialize obfs config per session
var obfsCfg *ObfsConfig
var obfsWriteState *ObfsState
@@ -693,6 +767,7 @@ func RunSession(
defer relayWg.Done()
defer sessCancel()
b := make([]byte, readBufSize)
var reusableWrap []byte
for {
n, _, readErr := pipeA.ReadFrom(b)
if readErr != nil {
@@ -701,7 +776,7 @@ func RunSession(
out := b[:n]
if useWrap {
if obfsCfg != nil && obfsWriteState != nil {
wrapped, wrapErr := obfsWrapPacket(tp.WrapKey, out, obfsCfg, obfsWriteState)
wrapped, wrapErr := obfsWrapPacketInto(reusableWrap, tp.WrapKey, out, obfsCfg, obfsWriteState)
if wrapErr != nil {
log.Printf("[СЕССИЯ #%d] OBFS wrap: %v", sessionID, wrapErr)
return
@@ -715,6 +790,18 @@ func RunSession(
}
}()
// Handshake, admission and experiment negotiation can all return early.
// Close both directions before joining so a failed path cannot leave a
// blocked pipe writer or TURN reader alive until process shutdown.
defer func() {
sessCancel()
_ = relay.Close()
_ = pipeA.Close()
_ = pipeB.Close()
relayWg.Wait()
sessionWg.Wait()
}()
// DTLS с поддержкой Connection ID (без SNI)
cert, err := selfsign.GenerateSelfSigned()
if err != nil {
@@ -722,6 +809,9 @@ func RunSession(
}
// Acquire handshake semaphore
if autoLease != nil {
autoLease.setStage("dtls")
}
select {
case handshakeSem <- struct{}{}:
case <-sessCtx.Done():
@@ -769,15 +859,12 @@ func RunSession(
})
defer stopDTLS()
stats.ActiveConnections.Add(1)
globalActiveConnections.Add(1)
defer func() {
stats.ActiveConnections.Add(-1)
globalActiveConnections.Add(-1)
}()
transportMode := tp.Experiment
// Запрос конфига
if getConfig && configCh != nil {
{ // Every worker must authenticate its device before joining the relay.
if autoLease != nil {
autoLease.setStage("registration")
}
conf, confErr := RequestConfig(
sessCtx,
dtlsConn,
@@ -786,6 +873,7 @@ func RunSession(
password,
deviceInfo,
transportSession,
pathprobe.Worker{Slot: uint32(sessionID), Attempt: d.workerAttempt.Add(1)},
)
if confErr != nil {
if _, limited := workerPolicyLimit(confErr); limited {
@@ -795,11 +883,34 @@ func RunSession(
if strings.Contains(errStr, "FATAL_AUTH") {
return false, confErr
}
if requireConfig {
return false, fmt.Errorf("регистрация нового подключения: %w", confErr)
return false, fmt.Errorf("регистрация нового подключения: %w", confErr)
}
if conf == "" {
return false, fmt.Errorf("сервер ещё не выдал конфигурацию")
}
transportMode = d.resolveTransport(conf)
if autoLease != nil {
autoLease.setStage("protocol")
}
if err := negotiateTransportExperiment(sessCtx, dtlsConn, conf, transportMode); err != nil {
return false, err
}
if autoLease != nil {
autoLease.setStage("confirmation")
if err := confirmConnectionPath(sessCtx, dtlsConn); err != nil {
return false, err
}
log.Printf("[ВОРКЕР #%d] Ошибка конфига: %v", sessionID, confErr)
} else if conf != "" {
if !startupTimer.Stop() || ctx.Err() != nil {
return false, context.DeadlineExceeded
}
if !autoLease.accept() {
return false, context.Canceled
}
if selectedMasqueProtocol != "" {
tp.Masque.markPreferred(selectedMasqueProtocol)
}
}
if getConfig && configCh != nil {
select {
case configCh <- conf:
configDelivered = true
@@ -811,22 +922,17 @@ func RunSession(
if onConfigDelivered != nil {
onConfigDelivered()
}
} else {
if requireConfig {
return false, fmt.Errorf("сервер ещё не выдал WireGuard-конфиг")
}
log.Printf("[ВОРКЕР #%d] Сервер ещё не выдал WireGuard-конфиг, повторим позже", sessionID)
}
}
log.Printf("[ВОРКЕР #%d] [READY] Туннель готов к работе ✓", sessionID)
stats.ActiveConnections.Add(1)
globalActiveConnections.Add(1)
defer func() {
stats.ActiveConnections.Add(-1)
globalActiveConnections.Add(-1)
}()
// New servers use this one-shot capability marker to bind every worker of
// a device to one stable WireGuard-side UDP source. An older server treats
// it as an invalid WireGuard datagram, then continues with the next packet.
if _, err := dtlsConn.Write([]byte(multipathRelayHello)); err != nil {
return false, fmt.Errorf("запуск multipath-реле: %w", err)
}
log.Printf("[ВОРКЕР #%d] [READY] Туннель готов к работе ✓", sessionID)
// Регистрация в диспетчере
slot := &WorkerSlot{
@@ -836,7 +942,32 @@ func RunSession(
SleepCh: make(chan struct{}, 1),
WakeAckCh: make(chan uint64, 1),
}
var uplinkReplacement atomic.Bool
if transportMode == experimentUplink {
slot.uplink = &uplinkQuality{id: sessionID, pacer: d.uplinkPacing}
slot.uplink.sleeping = d.deviceSleeping.Load
slot.uplink.probeWait = d.uplinkPacing.probes.Wait
slot.uplink.replace = func() bool {
if !d.canReplaceUplink(sessionID) {
return false
}
uplinkReplacement.Store(true)
return true
}
if replacingUplink {
slot.uplink.muted.Store(true)
slot.uplink.probation.Store(true)
}
}
var measuredPackets <-chan timedDatagram
if transportMetricsEnabled {
slot.queue = newTransportQueue(workerSendBuf)
measuredPackets = slot.queue.items
go slot.queue.run(sessCtx, "client_uplink", transportMode)
}
d.Register(slot)
d.uplinkRecovery.registered(sessionID)
recoveryComplete()
defer d.Unregister(slot)
var lastServerRxAt atomic.Int64
@@ -858,6 +989,20 @@ func RunSession(
return err == nil
}
if slot.uplink != nil {
proxyWg.Add(1)
go func() {
defer proxyWg.Done()
slot.uplink.run(sessCtx, func(p []byte) error {
dtlsWriteMu.Lock()
defer dtlsWriteMu.Unlock()
_ = dtlsConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
_, err := dtlsConn.Write(p)
return err
}, sessCancel)
}()
}
// DTLS Keepalive: prevents TURN allocation timeout and DTLS idle disconnect
go func() {
defer proxyWg.Done()
@@ -945,27 +1090,42 @@ func RunSession(
go func() {
defer proxyWg.Done()
defer sessCancel()
var framedPacket []byte
for {
var pkt []byte
select {
case <-sessCtx.Done():
return
case pkt, ok := <-slot.SendCh:
case queued := <-measuredPackets:
slot.queue.noteDequeue(queued)
pkt = queued.data
case p, ok := <-slot.SendCh:
if !ok {
return
}
userTraffic := isWireGuardUserDataPacket(pkt)
dtlsWriteMu.Lock()
_ = dtlsConn.SetWriteDeadline(time.Now().Add(sessionReadTimeout))
_, writeErr := dtlsConn.Write(pkt)
dtlsWriteMu.Unlock()
putPktBuf(pkt)
if writeErr != nil {
log.Printf("[ВОРКЕР #%d] Ошибка Writer: %v", sessionID, writeErr)
return
}
if userTraffic {
d.noteUserTrafficSent(time.Now())
}
pkt = p
}
userTraffic := d.isUserPacket(pkt)
writeStarted := time.Now()
dtlsWriteMu.Lock()
_ = dtlsConn.SetWriteDeadline(time.Now().Add(sessionReadTimeout))
outgoing := pkt
if slot.uplink != nil && len(pkt) >= 4 && pkt[0] >= 1 && pkt[0] <= 4 && pkt[1] == 0 && pkt[2] == 0 && pkt[3] == 0 {
outgoing = slot.uplink.frame(framedPacket, pkt, pathprobe.Data)
framedPacket = outgoing[:0]
}
_, writeErr := dtlsConn.Write(outgoing)
dtlsWriteMu.Unlock()
if slot.queue != nil {
slot.queue.noteWrite(writeStarted, len(pkt), writeErr)
}
putPktBuf(pkt)
if writeErr != nil {
log.Printf("[ВОРКЕР #%d] Ошибка Writer: %v", sessionID, writeErr)
return
}
if userTraffic {
d.noteUserTrafficSent(time.Now())
}
}
}()
@@ -1005,6 +1165,9 @@ func RunSession(
}
lastServerRxAt.Store(time.Now().UnixNano())
if slot.queue != nil {
slot.queue.received.Add(uint64(n))
}
if _, policyErr := parseConfigResponse(string(pkt[:n])); policyErr != nil {
if maxWorkers, limited := workerPolicyLimit(policyErr); limited {
@@ -1023,11 +1186,15 @@ func RunSession(
putPktBuf(pkt)
continue
}
if slot.uplink != nil && slot.uplink.ack(pkt[:n], time.Now()) {
putPktBuf(pkt)
continue
}
if d.handleUpdateMetadataResponse(pkt[:n]) {
putPktBuf(pkt)
continue
}
if isWireGuardUserDataPacket(pkt[:n]) {
if d.isUserPacket(pkt[:n]) {
if d.noteUserTrafficResponse() {
log.Printf("[HEALTH] пользовательский трафик снова получает ответы")
}
@@ -1055,5 +1222,8 @@ func RunSession(
return configDelivered, &workerPolicyLimitError{maxWorkers: maxWorkers}
default:
}
if uplinkReplacement.Load() {
return configDelivered, errUplinkPathReplacement
}
return configDelivered, nil
}
+32
View File
@@ -0,0 +1,32 @@
package main
import (
"context"
"os"
"time"
)
// STOP and EOF cancel ctx just like SIGTERM. Keep handling termination after
// cancellation: some Android Process implementations send SIGTERM even from
// destroyForcibly. A stuck provider read must not prevent the next generation
// from starting. Normal deferred cleanup has time to release TURN allocations;
// the deadline stays within the Android parent's graceful shutdown budget.
func runNativeShutdownGuard(ctx context.Context, cancel context.CancelFunc, signals <-chan os.Signal, exit func(int), grace time.Duration) {
select {
case <-signals:
if ctx.Err() != nil {
exit(1)
return
}
cancel()
case <-ctx.Done():
}
timer := time.NewTimer(grace)
defer timer.Stop()
select {
case <-signals:
exit(1)
case <-timer.C:
exit(0)
}
}
+171
View File
@@ -0,0 +1,171 @@
package main
import (
"context"
"encoding/binary"
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"time"
)
// No addresses, payloads, keys or credentials enter these opt-in measurements.
// Histograms and counters are cumulative for one process-local path ID.
var transportMetricsEnabled bool
var transportMetricIDs atomic.Uint64
// These optional counters observe admission before the individual path queues.
// A locally dropped datagram cannot appear in the remote delivery receipts.
type uplinkIngressMetrics struct {
accepted, dropped, expired, dispatched atomic.Uint64
pacingWait transportHistogram
}
func (m *uplinkIngressMetrics) report(bulk chan timedDatagram) {
if !transportMetricsEnabled || bulk == nil {
return
}
b, _ := json.Marshal(map[string]any{
"side": "client_uplink_ingress", "at": time.Now().UTC().Format(time.RFC3339Nano),
"depth": len(bulk), "capacity": cap(bulk), "accepted": m.accepted.Load(),
"dropped": m.dropped.Load(), "dispatched": m.dispatched.Load(),
"expired": m.expired.Load(),
"pacing_wait_bins": m.pacingWait.snapshot(),
})
fmt.Printf("TRANSPORT_METRIC|%s\n", b)
}
func (w *WorkerSlot) offerData(p []byte) bool {
if w.queue != nil {
return w.queue.offer(p)
}
select {
case w.SendCh <- p:
return true
default:
return false
}
}
type timedDatagram struct {
data []byte
queued time.Time
}
type transportHistogram struct{ buckets [8]atomic.Uint64 }
func (h *transportHistogram) observe(d time.Duration) {
limits := [...]time.Duration{time.Millisecond, 3 * time.Millisecond, 10 * time.Millisecond, 30 * time.Millisecond, 100 * time.Millisecond, 300 * time.Millisecond, time.Second}
i := 0
for i < len(limits) && d > limits[i] {
i++
}
h.buckets[i].Add(1)
}
func (h *transportHistogram) snapshot() [8]uint64 {
var v [8]uint64
for i := range v {
v[i] = h.buckets[i].Load()
}
return v
}
type transportQueue struct {
items chan timedDatagram
id uint64
enqueued, bytes, full, written, received, writeErrors atomic.Uint64
wait, write transportHistogram
}
func newTransportQueue(capacity int) *transportQueue {
return &transportQueue{items: make(chan timedDatagram, capacity), id: transportMetricIDs.Add(1)}
}
func (q *transportQueue) offer(p []byte) bool {
select {
case q.items <- timedDatagram{p, time.Now()}:
q.enqueued.Add(1)
q.bytes.Add(uint64(len(p)))
return true
default:
q.full.Add(1)
return false
}
}
func (q *transportQueue) noteDequeue(p timedDatagram) { q.wait.observe(time.Since(p.queued)) }
func (q *transportQueue) noteWrite(start time.Time, n int, err error) {
q.write.observe(time.Since(start))
if err != nil {
q.writeErrors.Add(1)
} else {
q.written.Add(uint64(n))
}
}
func (q *transportQueue) report(side, mode string, final bool) {
if !transportMetricsEnabled {
return
}
v := map[string]any{"side": side, "mode": mode, "id": q.id, "at": time.Now().UTC().Format(time.RFC3339Nano), "final": final,
"depth": len(q.items), "capacity": cap(q.items), "enqueued": q.enqueued.Load(), "bytes": q.bytes.Load(), "full": q.full.Load(), "written_bytes": q.written.Load(), "received_bytes": q.received.Load(), "write_errors": q.writeErrors.Load(), "wait_bins": q.wait.snapshot(), "write_bins": q.write.snapshot()}
b, _ := json.Marshal(v)
fmt.Printf("TRANSPORT_METRIC|%s\n", b)
}
func (q *transportQueue) run(ctx context.Context, side, mode string) {
if !transportMetricsEnabled {
return
}
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
q.report(side, mode, true)
return
case <-t.C:
q.report(side, mode, false)
}
}
}
// Observe only visible WireGuard transport headers. A lower counter proves
// reordering/duplication, not packet loss. Key rotation uses a bounded map.
type transportOrder struct {
mu sync.Mutex
highest map[uint32]uint64
packets, late, maxBehind uint64
}
func (o *transportOrder) observe(p []byte) {
if !transportMetricsEnabled || len(p) < 32 || binary.LittleEndian.Uint32(p[:4]) != 4 {
return
}
key := binary.LittleEndian.Uint32(p[4:8])
seq := binary.LittleEndian.Uint64(p[8:16])
o.mu.Lock()
defer o.mu.Unlock()
if o.highest == nil {
o.highest = make(map[uint32]uint64)
}
high, ok := o.highest[key]
o.packets++
if ok && seq < high {
o.late++
if high-seq > o.maxBehind {
o.maxBehind = high - seq
}
}
if !ok || seq > high {
if !ok && len(o.highest) >= 8 {
clear(o.highest)
}
o.highest[key] = seq
}
}
func (o *transportOrder) report(side string) {
if !transportMetricsEnabled {
return
}
o.mu.Lock()
defer o.mu.Unlock()
b, _ := json.Marshal(map[string]any{"side": side, "packets": o.packets, "late_or_duplicate": o.late, "max_behind": o.maxBehind, "at": time.Now().UTC().Format(time.RFC3339Nano)})
fmt.Printf("TRANSPORT_ORDER|%s\n", b)
}
+102
View File
@@ -0,0 +1,102 @@
package main
import (
"context"
"errors"
"fmt"
"net"
"strings"
"time"
)
const experimentAuto = "auto"
const experimentStandard = "standard"
const experimentUplink = "uplink"
func validateTransportExperiment(value string) error {
switch value {
case experimentAuto, experimentStandard, experimentUplink:
return nil
}
return errors.New("unknown transport mode")
}
func negotiateTransportExperiment(ctx context.Context, connection net.Conn, config, mode string) error {
capability, marker := "", multipathRelayHello
switch mode {
case experimentUplink:
capability, marker = "uplink2", "WDTT_UPLINK2"
}
if capability != "" {
supported := supportsAdaptiveTransport(config)
if !supported {
return errors.New("FATAL_TRANSPORT: сервер изменил возможности транспорта; переподключите туннель")
}
}
if _, err := connection.Write([]byte(marker)); err != nil {
return err
}
if capability == "" {
return nil
}
_ = connection.SetReadDeadline(time.Now().Add(5 * time.Second))
stop := context.AfterFunc(ctx, func() { _ = connection.SetReadDeadline(time.Now()) })
defer stop()
defer connection.SetReadDeadline(time.Time{})
b := make([]byte, readBufSize)
for {
n, err := connection.Read(b)
if err != nil {
// A lost acknowledgement or a changing network is recoverable.
// Never stop every worker because one new path timed out.
return fmt.Errorf("согласование транспорта: %w", err)
}
if string(b[:n]) == "WDTT_TRANSPORT_OK1" {
return nil
}
// DTLS datagrams can arrive out of order. An already active device
// can receive traffic on this path before its ACK arrives. Drop these
// early data packets under the same fixed deadline, then await ACK.
if (mode == experimentUplink && n >= 4 && b[0] >= 1 && b[0] <= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0) ||
(n == 1 && b[0] == keepaliveByte) {
continue
}
return fmt.Errorf("FATAL_TRANSPORT: сервер прислал неверное подтверждение транспорта")
}
}
func (d *Dispatcher) isUserPacket(p []byte) bool { return isWireGuardUserDataPacket(p) }
// Resolve once per connection generation: all workers must agree on framing.
// Capabilities come from the authenticated GETCONF, never from an unauthenticated probe.
func (d *Dispatcher) resolveTransport(config string) string {
if d.experiment != experimentAuto {
return d.experiment
}
selected := uint32(1)
if supportsAdaptiveTransport(config) {
selected = 2
}
d.negotiatedTransport.CompareAndSwap(0, selected)
if d.negotiatedTransport.Load() == 2 {
return experimentUplink
}
return experimentStandard
}
func (d *Dispatcher) usesUplink() bool {
return d.experiment == experimentUplink || (d.experiment == experimentAuto && d.negotiatedTransport.Load() == 2)
}
func supportsAdaptiveTransport(config string) bool {
for _, line := range strings.Split(config, "\n") {
if values, ok := strings.CutPrefix(strings.TrimSpace(line), "# WDTT_TRANSPORTS="); ok {
for _, value := range strings.Split(values, ",") {
if strings.TrimSpace(value) == "uplink2" {
return true
}
}
}
}
return false
}
+329
View File
@@ -0,0 +1,329 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"sync"
"sync/atomic"
"time"
"wdtt.local/pathprobe"
)
// Uplink selection uses delivery evidence, not RTT rankings. A path with poor
// upload remains registered for download. After cooldown, full-size probes
// verify recovery without sacrificing user packets to a known failing path.
type uplinkQuality struct {
replace func() bool
probeWait func(context.Context) error
sleeping func() bool
failedProbes int
pacer *uplinkPacer
mu sync.Mutex
muted atomic.Bool
probation atomic.Bool
id int
next, expected, received uint64
baseExpected, baseReceived uint64
badSince time.Time
checkAt time.Time
probeEnd, probeReceived uint64
probeDeadline time.Time
pendingSince time.Time
silenceProbes int
silenceProbeAt time.Time
loss uint64
pacingEpoch uint64
}
func (q *uplinkQuality) frame(dst, payload []byte, kind byte) []byte {
q.mu.Lock()
defer q.mu.Unlock()
if kind == pathprobe.Data && len(payload) <= 160 {
return pathprobe.Frame(dst, payload, pathprobe.Bypass, 0)
}
p := pathprobe.Frame(dst, payload, kind, q.next)
if p != nil {
if q.next == q.expected {
q.pendingSince = time.Now()
}
q.next++
}
return p
}
func (q *uplinkQuality) ack(p []byte, now time.Time) bool {
expected, received, ok := pathprobe.ParseAck(p)
if !ok {
return false
}
q.mu.Lock()
defer q.mu.Unlock()
// Stale/forged counters must not alter scheduling or overflow subtraction.
if expected > q.next || expected < q.expected || received < q.received {
return true
}
deltaExpected, deltaReceived := expected-q.expected, received-q.received
sharedCongestion := false
if q.pacer != nil {
sharedCongestion = q.pacer.notePath(q, deltaExpected, deltaReceived, now)
// A persistently defective path is isolated locally. Its losses must
// not repeatedly throttle every other path while quarantine converges.
defer func() { q.pacer.observe(deltaExpected, deltaReceived, !q.muted.Load() && q.badSince.IsZero()) }()
}
if expected > q.expected {
q.silenceProbes = 0
q.silenceProbeAt = time.Time{}
if expected == q.next {
q.pendingSince = time.Time{}
} else {
q.pendingSince = now
}
}
q.expected = expected
q.received = received
if q.muted.Load() {
return true
}
if q.pacer != nil {
epoch := q.pacer.congestionEpoch.Load()
if epoch != q.pacingEpoch {
// Loss observed before a common backoff describes the old load.
// Re-test this path at the reduced budget before isolating it.
q.pacingEpoch = epoch
q.badSince = time.Time{}
q.baseExpected = expected
q.baseReceived = received
return true
}
}
if sharedCongestion {
q.badSince = time.Time{}
q.baseExpected = expected
q.baseReceived = received
return true
}
if expected < q.baseExpected || received < q.baseReceived {
return true
}
total := expected - q.baseExpected
got := received - q.baseReceived
if total < 64 || got > total {
return true
}
missing := total - got
q.loss = missing * 1000 / total
if missing*8 > total {
if q.badSince.IsZero() {
q.badSince = now
return true
}
if now.Sub(q.badSince) < 100*time.Millisecond {
return true
}
q.muted.Store(true)
q.reportLocked("loss")
q.checkAt = now.Add(10 * time.Second)
q.badSince = time.Time{}
if transportMetricsEnabled {
log.Printf("[ОТДАЧА] Канал #%d временно исключён из отправки: подтверждено %d/%d пакетов; приём сохранён", q.id, got, total)
}
} else {
q.badSince = time.Time{}
if total >= 128 {
q.baseExpected = expected
q.baseReceived = received
}
}
return true
}
func (q *uplinkQuality) forceOpen() uint64 {
q.mu.Lock()
defer q.mu.Unlock()
q.muted.Store(false)
q.pendingSince = time.Now()
q.silenceProbes = 0
q.silenceProbeAt = time.Time{}
q.reportLocked("fallback")
q.probeEnd = 0
q.baseExpected = q.expected
q.baseReceived = q.received
q.badSince = time.Time{}
return q.loss
}
func (q *uplinkQuality) lossScore() uint64 { q.mu.Lock(); defer q.mu.Unlock(); return q.loss }
// run owns probe scheduling. write must serialize with ordinary DTLS writes;
// no sleeps or remote waits occur under the dispatcher's lock.
func (q *uplinkQuality) run(ctx context.Context, write func([]byte) error, cancel context.CancelFunc) {
tick := time.NewTicker(250 * time.Millisecond)
defer tick.Stop()
payload := make([]byte, 1312)
for {
select {
case <-ctx.Done():
return
case now := <-tick.C:
q.mu.Lock()
if q.sleeping != nil && q.sleeping() {
// Doze is not evidence of a broken path. Keep recovery silent and
// restart its evidence window after wake instead of spending the
// phone's idle network/battery budget on full-size probes.
if !q.pendingSince.IsZero() {
q.pendingSince = now
}
q.silenceProbes = 0
q.silenceProbeAt = time.Time{}
q.probeEnd = 0
q.checkAt = now.Add(time.Second)
q.badSince = time.Time{}
q.mu.Unlock()
continue
}
if !q.muted.Load() {
if q.next-q.expected >= 1 && !q.pendingSince.IsZero() && now.Sub(q.pendingSince) >= 2*time.Second {
// A single missing tail packet during an otherwise idle phase
// is not a dead channel. Request delivery evidence twice before
// quarantine, without sacrificing ordinary user traffic.
if now.Before(q.silenceProbeAt) {
q.mu.Unlock()
continue
}
if q.silenceProbes < 2 {
q.silenceProbes++
q.silenceProbeAt = now.Add(2 * time.Second)
p := pathprobe.Frame(nil, payload, pathprobe.Probe, q.next)
q.next++
q.mu.Unlock()
if q.probeWait != nil && q.probeWait(ctx) != nil {
return
}
if write(p) != nil {
cancel()
return
}
continue
}
q.muted.Store(true)
q.loss = 1000
q.checkAt = now.Add(10 * time.Second)
q.reportLocked("no_progress")
if transportMetricsEnabled {
log.Printf("[ОТДАЧА] Канал #%d временно исключён из отправки: нет подтверждения доставки; приём сохранён", q.id)
}
}
q.mu.Unlock()
continue
}
if q.probeEnd != 0 {
if now.Before(q.probeDeadline) {
q.mu.Unlock()
continue
}
good := q.expected >= q.probeEnd && q.received >= q.probeReceived && q.received-q.probeReceived >= 32
q.probeEnd = 0
q.checkAt = now.Add(10 * time.Second)
if good {
q.failedProbes = 0
q.probation.Store(false)
q.muted.Store(false)
q.pendingSince = time.Time{}
q.reportLocked("recovered")
q.baseExpected = q.expected
q.baseReceived = q.received
q.badSince = time.Time{}
if transportMetricsEnabled {
log.Printf("[ОТДАЧА] Канал #%d снова участвует в отправке после проверки доставки", q.id)
}
} else {
q.failedProbes++
}
shouldReplace := !good && q.failedProbes >= 2 && q.replace != nil
q.mu.Unlock()
if shouldReplace && q.replace() {
q.mu.Lock()
q.reportLocked("replace")
q.mu.Unlock()
if transportMetricsEnabled {
log.Printf("[ОТДАЧА] Канал #%d не восстановил доставку после проверок; заменяем только этот канал", q.id)
}
cancel()
return
}
continue
}
if now.Before(q.checkAt) {
q.mu.Unlock()
continue
}
q.probeReceived = q.received
// Reserve the entire probe sequence under one lock. Ordinary traffic has
// drained during cooldown; an emergency fallback cancels this probation.
frames := make([][]byte, 32)
for i := range frames {
frames[i] = pathprobe.Frame(nil, payload, pathprobe.Probe, q.next)
q.next++
}
q.probeEnd = q.next
q.probeDeadline = now.Add(time.Second)
q.mu.Unlock()
for _, p := range frames {
if ctx.Err() != nil {
return
}
if q.probeWait != nil && q.probeWait(ctx) != nil {
return
}
if write(p) != nil {
cancel()
return
}
}
q.mu.Lock()
q.probeDeadline = time.Now().Add(time.Second)
q.mu.Unlock()
}
}
}
// Called under q.mu; diagnostic output contains only local IDs and counters.
func (q *uplinkQuality) reportLocked(event string) {
if !transportMetricsEnabled {
return
}
b, _ := json.Marshal(map[string]any{"side": "uplink_delivery", "mode": "uplink", "id": q.id, "at": time.Now().UTC().Format(time.RFC3339Nano), "event": event, "sent": q.next, "expected": q.expected, "received": q.received, "muted": q.muted.Load()})
fmt.Printf("TRANSPORT_METRIC|%s\n", b)
}
func ensureUplinkServiceFloor(ws []*WorkerSlot, wakeGeneration uint64, deviceSleeping bool) {
// Keep a last-resort path only when none is usable. Reopening a fixed
// fraction of the requested workers reintroduced proven losses whenever
// a small hash set supplied many defective paths. Healthy paths determine
// usable capacity; the slider must not force known failures back into it.
healthy := 0
for _, w := range ws {
if !workerEligibleForWakeGeneration(w, wakeGeneration, deviceSleeping) || (w.uplink != nil && w.uplink.probation.Load()) {
continue
}
if w.uplink == nil || !w.uplink.muted.Load() {
healthy++
}
}
floor := 1
for healthy < floor {
var best *WorkerSlot
for _, w := range ws {
if !workerEligibleForWakeGeneration(w, wakeGeneration, deviceSleeping) || w.uplink == nil || w.uplink.probation.Load() || !w.uplink.muted.Load() {
continue
}
if best == nil || w.uplink.lossScore() < best.uplink.lossScore() {
best = w
}
}
if best == nil {
break
}
best.uplink.forceOpen()
healthy++
}
}
+207
View File
@@ -0,0 +1,207 @@
package main
import (
"context"
"encoding/json"
"fmt"
"golang.org/x/time/rate"
"sync"
"sync/atomic"
"time"
)
// Limit aggregate bursts before they enter independent TURN queues. TCP ACKs
// and handshakes bypass pacing; bulk delivery reports adjust the shared budget.
// This is confined to the opt-in uplink transport, never a subscription limit.
type uplinkPacer struct {
limiter *rate.Limiter
probes *rate.Limiter
mu sync.Mutex
expected, received uint64
mbps float64
offeredBytes atomic.Int64
lastAdjust time.Time
idleTicks int
previousUsageMbps float64
paths map[*uplinkQuality]uplinkPathFeedback
sharedSince time.Time
sharedUntil time.Time
lastSharedAdjust time.Time
congestionEpoch atomic.Uint64
}
type uplinkPathFeedback struct {
start, latest time.Time
expected, received uint64
}
func (p *uplinkPacer) registerPath(q *uplinkQuality) {
p.mu.Lock()
defer p.mu.Unlock()
if p.paths == nil {
p.paths = make(map[*uplinkQuality]uplinkPathFeedback)
}
p.paths[q] = uplinkPathFeedback{}
}
func (p *uplinkPacer) unregisterPath(q *uplinkQuality) {
p.mu.Lock()
defer p.mu.Unlock()
delete(p.paths, q)
}
// Several paths share one device uplink. Widespread loss first needs a common
// budget reduction, rather than quarantining every path and losing feedback.
// A minority still follows normal isolation; persistent failure can defer it
// for at most two seconds. State is bounded by registered live paths.
func (p *uplinkPacer) notePath(q *uplinkQuality, expected, received uint64, now time.Time) bool {
p.mu.Lock()
defer p.mu.Unlock()
sample, exists := p.paths[q]
if !exists || q.muted.Load() {
return false
}
if sample.start.IsZero() || now.Sub(sample.start) >= time.Second {
sample = uplinkPathFeedback{start: now}
}
sample.latest = now
sample.expected += expected
sample.received += received
p.paths[q] = sample
active, participating, bad := 0, 0, 0
var totalExpected, totalReceived uint64
for path, feedback := range p.paths {
if path.muted.Load() {
continue
}
active++
if feedback.expected < 32 || feedback.latest.IsZero() || now.Sub(feedback.latest) >= time.Second {
continue
}
participating++
totalExpected += feedback.expected
totalReceived += feedback.received
if feedback.received < feedback.expected && feedback.expected-feedback.received > feedback.expected/50 {
bad++
}
}
if participating >= max(2, (active+1)/2) && bad >= 2 && bad*2 > participating && totalExpected >= 128 {
if p.sharedSince.IsZero() {
p.sharedSince = now
}
if now.Sub(p.sharedSince) < 2*time.Second {
p.sharedUntil = now.Add(500 * time.Millisecond)
deadline := p.sharedSince.Add(2 * time.Second)
if p.sharedUntil.After(deadline) {
p.sharedUntil = deadline
}
if now.Sub(p.sharedSince) >= 100*time.Millisecond && (p.lastSharedAdjust.IsZero() || now.Sub(p.lastSharedAdjust) >= 250*time.Millisecond) {
previousBudget := p.mbps
p.mbps = max(8, p.mbps*.8)
if p.mbps < previousBudget {
p.congestionEpoch.Add(1)
}
p.limiter.SetLimitAt(now, rate.Limit(p.mbps*1e6/8))
p.lastSharedAdjust = now
if transportMetricsEnabled {
b, _ := json.Marshal(map[string]any{"side": "uplink_shared_congestion", "at": now.UTC().Format(time.RFC3339Nano), "mbps": p.mbps, "active": active, "participating": participating, "bad": bad, "expected": totalExpected, "received": totalReceived})
fmt.Printf("TRANSPORT_METRIC|%s\n", b)
}
}
}
} else if !now.Before(p.sharedUntil) {
// A recovered majority ends the episode. Continuing widespread failure
// never renews the bounded grace period.
p.sharedSince = time.Time{}
}
return now.Before(p.sharedUntil)
}
func newUplinkPacer() *uplinkPacer {
return &uplinkPacer{limiter: rate.NewLimiter(rate.Limit(64e6/8), 8*1500), probes: rate.NewLimiter(256, 4), mbps: 64}
}
func (p *uplinkPacer) wait(ctx context.Context, n int) error {
if n <= 160 {
return nil
}
// Include framing, DTLS, wrapping, TURN and the outer IP/UDP header.
if err := p.limiter.WaitN(ctx, n+128); err != nil {
return err
}
p.offeredBytes.Add(int64(n + 128))
return nil
}
func (p *uplinkPacer) observe(expected, received uint64, eligible bool) {
if !eligible {
return
}
p.mu.Lock()
p.expected += expected
p.received += received
p.mu.Unlock()
}
func (p *uplinkPacer) adjust(now time.Time) {
p.mu.Lock()
defer p.mu.Unlock()
seconds := 1.0
if !p.lastAdjust.IsZero() {
seconds = max(.1, now.Sub(p.lastAdjust).Seconds())
}
p.lastAdjust = now
offered := p.offeredBytes.Swap(0)
expected, received := p.expected, p.received
p.expected = 0
p.received = 0
if offered == 0 {
p.idleTicks++
} else {
p.idleTicks = 0
}
if p.idleTicks >= 5 {
p.mbps = min(64, p.mbps)
p.limiter.SetLimitAt(now, rate.Limit(p.mbps*1e6/8))
}
usageMbps := float64(offered) * 8 / 1e6 / seconds
recentUsageMbps := max(usageMbps, p.previousUsageMbps)
p.previousUsageMbps = usageMbps
if expected < 128 {
return
}
missing := uint64(0)
if expected > received {
missing = expected - received
}
loss := float64(missing) / float64(expected)
sharedAdjustment := !p.lastSharedAdjust.IsZero() && now.Sub(p.lastSharedAdjust) < time.Second
if sharedAdjustment {
// The fast common response already reduced this budget. Do not apply
// another reduction using receipts from before that adjustment.
} else if loss > .02 {
// Back off relative to traffic actually carried, not a stale ceiling
// learned when application demand was much lower than that ceiling.
previousBudget := p.mbps
p.mbps = max(8, min(p.mbps*.8, recentUsageMbps*.85))
if p.mbps < previousBudget {
p.congestionEpoch.Add(1)
}
} else if loss < .005 && usageMbps >= p.mbps*.7 {
p.mbps = min(512, p.mbps*1.15)
}
p.limiter.SetLimitAt(now, rate.Limit(p.mbps*1e6/8))
if transportMetricsEnabled {
b, _ := json.Marshal(map[string]any{"side": "uplink_pacing", "mode": "uplink", "id": 0, "at": now.UTC().Format(time.RFC3339Nano), "mbps": p.mbps, "offered_mbps": usageMbps, "expected": expected, "received": received})
fmt.Printf("TRANSPORT_METRIC|%s\n", b)
}
}
func (p *uplinkPacer) run(ctx context.Context) {
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
p.adjust(now)
}
}
}
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"errors"
"sync"
"time"
)
var errUplinkPathReplacement = errors.New("uplink delivery path replacement")
// One dispatcher owns the budget, so separate credential groups cannot each
// start their own replacement storm. Credentials are reused by WorkerGroup.
type uplinkRecovery struct {
mu sync.Mutex
active map[int]bool
pending map[int]bool
next map[int]time.Time
attempts map[int]int
nextGlobal time.Time
capacityUntil time.Time
}
func (r *uplinkRecovery) acquire(id int, now time.Time) bool {
r.mu.Lock()
defer r.mu.Unlock()
if len(r.active) >= 2 || r.active[id] || now.Before(r.nextGlobal) || now.Before(r.next[id]) || now.Before(r.capacityUntil) {
return false
}
if r.active == nil {
r.active = make(map[int]bool)
r.pending = make(map[int]bool)
r.next = make(map[int]time.Time)
r.attempts = make(map[int]int)
}
r.active[id] = true
r.pending[id] = true
r.attempts[id] = min(4, r.attempts[id]+1)
r.next[id] = now.Add(30 * time.Second * time.Duration(1<<(r.attempts[id]-1)))
r.nextGlobal = now.Add(5 * time.Second)
return true
}
func (r *uplinkRecovery) capacityLimited(now time.Time) {
r.mu.Lock()
r.capacityUntil = now.Add(30 * time.Second)
r.mu.Unlock()
}
// Capture the previous attempt's permit before entering RunSession. A permit
// acquired later by this session must survive its teardown until the following
// handshake finishes or fails. The returned release is idempotent.
func (r *uplinkRecovery) completion(id int) (bool, func()) {
r.mu.Lock()
held := r.active[id]
needsProbe := r.pending[id]
r.mu.Unlock()
var once sync.Once
return needsProbe, func() {
if held {
once.Do(func() { r.mu.Lock(); delete(r.active, id); r.mu.Unlock() })
}
}
}
// A failed handshake releases the concurrency permit, but must not turn the
// following retry into an unverified ordinary path. Clear probation only once
// a registered successor owns its own full-size delivery check.
func (r *uplinkRecovery) registered(id int) {
r.mu.Lock()
delete(r.pending, id)
r.mu.Unlock()
}
func (d *Dispatcher) canReplaceUplink(id int) bool {
if d.ctx.Err() != nil || d.deviceSleeping.Load() {
return false
}
ws := d.workers.Load()
if ws == nil {
return false
}
healthy := 0
for _, w := range *ws {
if w.ID != id && workerEligibleForWakeGeneration(w, d.wakeGeneration.Load(), false) &&
(w.uplink == nil || !w.uplink.muted.Load()) {
healthy++
}
}
// Never tear down the remaining usable service to improve a sick path.
return healthy >= 1 && d.uplinkRecovery.acquire(id, time.Now())
}
+117
View File
@@ -0,0 +1,117 @@
package main
import (
"encoding/binary"
"net"
"sync"
"sync/atomic"
"time"
)
// Pion owns allocation transactions, but Client.Close does not close the
// caller-supplied network socket. Keep the two lifetimes together, including
// TCP/TLS and MASQUE streams, so retrying a worker cannot leak a reader/socket.
type ownedTURNAllocation struct {
net.PacketConn
transport net.PacketConn
closeClient func()
deletion *turnDeletionTransport
once sync.Once
err error
}
func (c *ownedTURNAllocation) Close() error {
c.once.Do(func() {
// Send allocation deletion while its transport is still available.
if c.deletion != nil {
c.deletion.closing.Store(true)
}
c.err = c.PacketConn.Close()
if c.deletion != nil && c.err == nil {
c.deletion.wait(750 * time.Millisecond)
}
c.closeClient()
if err := c.transport.Close(); c.err == nil {
c.err = err
}
})
return c.err
}
// Keep the socket and Pion retransmission timer alive for the zero-lifetime
// Refresh response. Closing them immediately after sending one UDP datagram
// can leave the remote allocation occupied until its ordinary expiry.
// Only teardown inspects STUN; normal traffic takes a single atomic branch.
type turnDeletionTransport struct {
net.PacketConn
closing atomic.Bool
mu sync.Mutex
transaction [12]byte
pending bool
ack chan struct{}
once sync.Once
}
func deletionTransaction(p []byte, kind uint16) ([12]byte, bool) {
var id [12]byte
if len(p) < 20 || binary.BigEndian.Uint16(p[:2]) != kind || binary.BigEndian.Uint32(p[4:8]) != 0x2112a442 {
return id, false
}
n := 20 + int(binary.BigEndian.Uint16(p[2:4]))
if n != len(p) {
return id, false
}
for at := 20; at+4 <= n; {
attr, size := binary.BigEndian.Uint16(p[at:at+2]), int(binary.BigEndian.Uint16(p[at+2:at+4]))
at += 4
if at+size > n {
return id, false
}
if attr == 0x000d && size == 4 && binary.BigEndian.Uint32(p[at:at+4]) == 0 {
copy(id[:], p[8:20])
return id, true
}
at += (size + 3) &^ 3
}
return id, false
}
func (c *turnDeletionTransport) WriteTo(p []byte, addr net.Addr) (int, error) {
if c.closing.Load() {
if id, ok := deletionTransaction(p, 0x0004); ok {
c.mu.Lock()
c.transaction = id
c.pending = true
c.mu.Unlock()
}
}
return c.PacketConn.WriteTo(p, addr)
}
func (c *turnDeletionTransport) ReadFrom(p []byte) (int, net.Addr, error) {
n, addr, err := c.PacketConn.ReadFrom(p)
if c.closing.Load() && n > 0 {
if id, ok := deletionTransaction(p[:n], 0x0104); ok {
c.mu.Lock()
match := c.pending && c.transaction == id
c.mu.Unlock()
if match {
c.once.Do(func() { close(c.ack) })
}
}
}
return n, addr, err
}
func (c *turnDeletionTransport) wait(timeout time.Duration) {
c.mu.Lock()
pending := c.pending
c.mu.Unlock()
if !pending {
return
}
t := time.NewTimer(timeout)
defer t.Stop()
select {
case <-c.ack:
case <-t.C:
}
}
+3 -1
View File
@@ -257,7 +257,9 @@ func sessionTURNCandidatesForAttempt(
}
}
if preferStream {
// The shared policy sets the order and needs every fallback candidate,
// including TCP at an address advertised by the provider as UDP-only.
if preferStream || (tp != nil && tp.Auto != nil) {
addStreamCandidates(true)
addLegacyUDP()
} else {