sockopt_linux.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package internet
  2. import (
  3. "syscall"
  4. )
  5. const (
  6. // For incoming connections.
  7. TCP_FASTOPEN = 23
  8. // For out-going connections.
  9. TCP_FASTOPEN_CONNECT = 30
  10. )
  11. func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error {
  12. if config.Mark != 0 {
  13. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil {
  14. return newError("failed to set SO_MARK").Base(err)
  15. }
  16. }
  17. if isTCPSocket(network) {
  18. switch config.Tfo {
  19. case SocketConfig_Enable:
  20. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN_CONNECT, 1); err != nil {
  21. return newError("failed to set TCP_FASTOPEN_CONNECT=1").Base(err)
  22. }
  23. case SocketConfig_Disable:
  24. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN_CONNECT, 0); err != nil {
  25. return newError("failed to set TCP_FASTOPEN_CONNECT=0").Base(err)
  26. }
  27. }
  28. }
  29. if config.Tproxy {
  30. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
  31. return newError("failed to set IP_TRANSPARENT").Base(err)
  32. }
  33. }
  34. return nil
  35. }
  36. func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error {
  37. if isTCPSocket(network) {
  38. switch config.Tfo {
  39. case SocketConfig_Enable:
  40. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN, 1); err != nil {
  41. return newError("failed to set TCP_FASTOPEN=1").Base(err)
  42. }
  43. case SocketConfig_Disable:
  44. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, TCP_FASTOPEN, 0); err != nil {
  45. return newError("failed to set TCP_FASTOPEN=0").Base(err)
  46. }
  47. }
  48. }
  49. if config.Tproxy {
  50. if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
  51. return newError("failed to set IP_TRANSPARENT").Base(err)
  52. }
  53. }
  54. return nil
  55. }