diff --git a/mobile/protect.go b/mobile/protect.go index 3349c3c..9a38aa7 100644 --- a/mobile/protect.go +++ b/mobile/protect.go @@ -1,6 +1,8 @@ package mobile import ( + "errors" + "fmt" "sync/atomic" "syscall" @@ -13,6 +15,8 @@ type Protector interface { Protect(fd int) bool } +var ErrProtect = errors.New("mobile: socket protect failed") //nolint:gochecknoglobals // sentinel для errors.Is + var protector atomic.Pointer[Protector] // SetProtect устанавливает обработчик защиты сокетов хоста (nil - no-op). @@ -24,7 +28,14 @@ func SetProtect(p Protector) { } protector.Store(&p) netctl.SetControl(func(_, _ string, c syscall.RawConn) error { - return c.Control(func(fd uintptr) { p.Protect(int(fd)) }) + ok := false + if err := c.Control(func(fd uintptr) { ok = p.Protect(int(fd)) }); err != nil { + return fmt.Errorf("socket control: %w", err) + } + if !ok { + return ErrProtect + } + return nil }) } diff --git a/mobile/tunnel_test.go b/mobile/tunnel_test.go index 0abaccf..57e3753 100644 --- a/mobile/tunnel_test.go +++ b/mobile/tunnel_test.go @@ -12,6 +12,7 @@ import ( "github.com/samosvalishe/free-turn-proxy/internal/config" "github.com/samosvalishe/free-turn-proxy/internal/logx" + "github.com/samosvalishe/free-turn-proxy/internal/netctl" "github.com/samosvalishe/free-turn-proxy/internal/tunnel" ) @@ -369,6 +370,28 @@ func TestProtectFDReturnsStatus(t *testing.T) { } } +func TestSetProtectFailsDial(t *testing.T) { + p := &testProtector{} + SetProtect(p) + t.Cleanup(func() { SetProtect(nil) }) + + d := net.Dialer{Control: netctl.Apply} + conn, err := d.Dial("udp", "127.0.0.1:9") + if err == nil { + _ = conn.Close() + } + if !errors.Is(err, ErrProtect) { + t.Fatalf("Dial = %v, want ErrProtect", err) + } + + p.ok = true + conn, err = d.Dial("udp", "127.0.0.1:9") + if err != nil { + t.Fatalf("Dial with protect ok = %v", err) + } + _ = conn.Close() +} + type stubRebinder struct { stubBackend rebound int