diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f478562..bb6be96 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -107,7 +107,7 @@ jobs: id: tags run: | version="${GITHUB_REF_NAME#v}" - repo="ghcr.io/${{ github.repository_owner }}/freeturn-awg" + repo=$(echo "ghcr.io/${{ github.repository_owner }}/freeturn-awg" | tr '[:upper:]' '[:lower:]') { echo "version=${version}" echo "list</dev/null | awk '{for(i=1;i/dev/null; then + iptables "${tbl[@]}" -A "$@" + fi +} + if [ -n "$WAN" ] && [ -n "$NET" ]; then - iptables -A FORWARD -i "$IFACE" -j ACCEPT - iptables -A FORWARD -o "$IFACE" -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT - iptables -t nat -A POSTROUTING -s "$NET" -o "$WAN" -j MASQUERADE + _ipt FORWARD -i "$IFACE" -j ACCEPT + _ipt FORWARD -o "$IFACE" -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + _ipt -t nat POSTROUTING -s "$NET" -o "$WAN" -j MASQUERADE # -o WAN: ответный SYN-ACK из интернета несёт MSS 1460, режем по PMTU пути. # -o IFACE: страховка от клиента, забывшего MTU. - iptables -t mangle -A FORWARD -o "$WAN" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu - iptables -t mangle -A FORWARD -o "$IFACE" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss "$((MTU - 40))" + _ipt -t mangle FORWARD -o "$WAN" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu + _ipt -t mangle FORWARD -o "$IFACE" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss "$((MTU - 40))" else echo "ft-awg: WAN or subnet not detected (wan='$WAN' net='$NET'); NAT skipped" >&2 fi diff --git a/docs/deploy.md b/docs/deploy.md index 3e169f6..569ba13 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -132,7 +132,7 @@ openssl rand -hex 32 | `AWG_IFACE` | `awg0` | Имя интерфейса | | `AWG_LOG_LEVEL` | `error` | Логи демона: `error` \| `verbose` \| `silent` | -NAT настраивается только для IPv4. +NAT настраивается только для IPv4 (контейнер использует network_mode: host и добавляет правила iptables в стек хоста). --- diff --git a/internal/tunnel/awg/awg.go b/internal/tunnel/awg/awg.go index c39466d..5ee0aeb 100644 --- a/internal/tunnel/awg/awg.go +++ b/internal/tunnel/awg/awg.go @@ -20,7 +20,7 @@ type Deps struct { Bind conn.Bind Log logx.Logger // Protect исключает сокеты bind из туннеля (VpnService.protect); nil - бэкенд поверх пайпа релея. - Protect func(fd int) + Protect func(fd int) bool } type Backend struct { @@ -109,15 +109,21 @@ func (b *Backend) protectBind(dev *device.Device) { } protected := 0 if fd, err := peek.PeekLookAtSocketFd4(); err == nil { - b.deps.Protect(fd) - protected++ + if b.deps.Protect(fd) { + protected++ + } else { + b.deps.Log.Warnf("tunnel: failed to protect ipv4 socket fd=%d", fd) + } } if fd, err := peek.PeekLookAtSocketFd6(); err == nil { - b.deps.Protect(fd) - protected++ + if b.deps.Protect(fd) { + protected++ + } else { + b.deps.Log.Warnf("tunnel: failed to protect ipv6 socket fd=%d", fd) + } } if protected == 0 { - b.deps.Log.Warnf("tunnel: no bind socket to protect") + b.deps.Log.Warnf("tunnel: no bind socket protected") } } @@ -135,6 +141,7 @@ func (b *Backend) Down() error { return nil } +// Stats возвращает текущие счетчики трафика туннеля. func (b *Backend) Stats() (tunnel.Stats, error) { b.mu.Lock() dev := b.dev diff --git a/mobile/README.md b/mobile/README.md index 573f324..5e62f79 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -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`. diff --git a/mobile/api.go b/mobile/api.go index 985a5a3..e91d586 100644 --- a/mobile/api.go +++ b/mobile/api.go @@ -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) diff --git a/mobile/protect.go b/mobile/protect.go index ceddcb6..3349c3c 100644 --- a/mobile/protect.go +++ b/mobile/protect.go @@ -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 } diff --git a/mobile/tunnel_test.go b/mobile/tunnel_test.go index ea1566b..eb29b6b 100644 --- a/mobile/tunnel_test.go +++ b/mobile/tunnel_test.go @@ -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) + } +}