fix(tunnel): обработка защиты сокетов и стабильность прямого режима

This commit is contained in:
samosvalishe committed 2026-09-07 02:37:54 +03:00
1 parent 67f9a4fe4e
commit 1cc5e93d03
8 files changed
+102 -20

No files matched your search

+4 -2
View File
@@ -125,14 +125,16 @@ WireGuard общается с релеем через in-memory `netconn.PacketP
```kotlin
pfd = builder.establish()!!
Mobile.startDirectTunnel(wgConf, 1376, pfd.dup().detachFd().toLong())
Mobile.startDirectTunnel(wgConf, 1376L, pfd.dup().detachFd().toLong())
```
Отличия от `StartTunnel`:
* каждый `[Peer]` обязан нести `Endpoint` в виде `ip:port` - bind устройства не резолвит имена;
* каждый `[Peer]` обязан нести `Endpoint` в виде `ip:port` - bind устройства не резолвит имена (если в конфиге указан домен, хост должен отрезолвить его до вызова);
* `SetProtect` обязателен: сокеты открывает bind устройства, без защиты трафик заворачивается обратно в туннель;
* состояние и метрики отслеживаются через `GetState()` (polling); push-события `OnState` в `EventSink` генерируются только для релейных сессий;
* `GetState()` держит `connected` с первого handshake и уходит в `connecting`, только если handshake старше 180 с при идущем tx; `Streams`/`Total` всегда 1;
* `Wake()` в прямом режиме - no-op; при смене сети или выходе устройства из сна вызывается `Reconnect()`;
* `Reconnect()` пересоздаёт и заново защищает сокеты - этого хватает при смене сети, перезапуск не нужен;
* `Restart` работает только с JSON-конфигурацией: для смены параметров прямого туннеля нужен `Stop` и новый `StartDirectTunnel`;
* `mtu` идёт только в валидацию и логи: tun создаёт платформа, MTU для неё даёт `ParseTunnelConfig`.
+6 -2
View File
@@ -174,8 +174,6 @@ func Wake() {
// Reconnect пересоздаёт TURN-аллокации, не трогая туннель и tun-дескриптор.
// В прямом режиме вместо них пересоздаются сокеты bind.
func Reconnect() {
mu.Lock()
defer mu.Unlock()
l := current.Load()
if l == nil {
return
@@ -184,6 +182,12 @@ func Reconnect() {
l.sess.Reconnect()
return
}
mu.Lock()
defer mu.Unlock()
l = current.Load()
if l == nil || !l.direct() {
return
}
if r, ok := l.tunnel.backend.(tunnel.Rebinder); ok {
if err := r.Rebind(); err != nil {
coreLog().Warnf("%v", err)
+3 -2
View File
@@ -28,8 +28,9 @@ func SetProtect(p Protector) {
})
}
func protectFD(fd int) {
func protectFD(fd int) bool {
if p := protector.Load(); p != nil {
(*p).Protect(fd)
return (*p).Protect(fd)
}
return false
}
+57
View File
@@ -334,3 +334,60 @@ func TestFillRatesFirstCall(t *testing.T) {
t.Errorf("rates = %d/%d, want 0/0", s.TxRate, s.RxRate)
}
}
type testProtector struct {
protected []int
ok bool
}
func (p *testProtector) Protect(fd int) bool {
p.protected = append(p.protected, fd)
return p.ok
}
func TestProtectFDReturnsStatus(t *testing.T) {
SetProtect(nil)
if protectFD(42) {
t.Error("protectFD() = true when no protector set")
}
p := &testProtector{ok: true}
SetProtect(p)
t.Cleanup(func() { SetProtect(nil) })
if !protectFD(42) {
t.Error("protectFD(42) = false, want true")
}
if len(p.protected) != 1 || p.protected[0] != 42 {
t.Errorf("protected = %v, want [42]", p.protected)
}
p.ok = false
if protectFD(43) {
t.Error("protectFD(43) = true, want false when protect fails")
}
}
type stubRebinder struct {
stubBackend
rebound int
}
func (s *stubRebinder) Rebind() error {
s.rebound++
return nil
}
func TestDirectReconnectInvokesRebind(t *testing.T) {
reb := &stubRebinder{}
current.Store(&live{
tunnel: &tunnelParts{backend: reb},
})
t.Cleanup(func() { current.Store(nil) })
Reconnect()
if reb.rebound != 1 {
t.Errorf("rebound = %d, want 1", reb.rebound)
}
}