control_unix.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:build !solaris && !windows
  7. // +build !solaris,!windows
  8. package dialer
  9. import (
  10. "log/slog"
  11. "syscall"
  12. "golang.org/x/sys/unix"
  13. )
  14. var SupportsReusePort = false
  15. func init() {
  16. fd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, unix.IPPROTO_IP)
  17. if err != nil {
  18. l.Debugln("Failed to create a socket", err)
  19. return
  20. }
  21. defer func() { _ = unix.Close(fd) }()
  22. err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  23. switch {
  24. case err == unix.ENOPROTOOPT || err == unix.EINVAL:
  25. slog.Debug("SO_REUSEPORT not supported")
  26. case err != nil:
  27. l.Debugln("Unknown error when determining SO_REUSEPORT support", err)
  28. default:
  29. slog.Debug("SO_REUSEPORT supported")
  30. SupportsReusePort = true
  31. }
  32. }
  33. func ReusePortControl(_, _ string, c syscall.RawConn) error {
  34. if !SupportsReusePort {
  35. return nil
  36. }
  37. var opErr error
  38. err := c.Control(func(fd uintptr) {
  39. opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
  40. })
  41. if err != nil {
  42. return err
  43. }
  44. return opErr
  45. }