sing-box/common/redir/redir_linux.go

38 lines
1.0 KiB
Go
Raw Normal View History

2022-07-15 08:42:02 +08:00
package redir
import (
"net"
"net/netip"
2022-08-16 18:19:48 +08:00
"os"
2022-07-15 08:42:02 +08:00
"syscall"
2022-08-16 18:19:48 +08:00
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/control"
2022-07-15 08:42:02 +08:00
M "github.com/sagernet/sing/common/metadata"
)
func GetOriginalDestination(conn net.Conn) (destination netip.AddrPort, err error) {
2022-08-16 18:19:48 +08:00
syscallConn, ok := common.Cast[syscall.Conn](conn)
if !ok {
return netip.AddrPort{}, os.ErrInvalid
2022-07-15 08:42:02 +08:00
}
2022-08-16 18:19:48 +08:00
err = control.Conn(syscallConn, func(fd uintptr) error {
const SO_ORIGINAL_DST = 80
if conn.RemoteAddr().(*net.TCPAddr).IP.To4() != nil {
raw, err := syscall.GetsockoptIPv6Mreq(int(fd), syscall.IPPROTO_IP, SO_ORIGINAL_DST)
if err != nil {
return err
}
destination = netip.AddrPortFrom(M.AddrFromIP(raw.Multiaddr[4:8]), uint16(raw.Multiaddr[2])<<8+uint16(raw.Multiaddr[3]))
} else {
raw, err := syscall.GetsockoptIPv6MTUInfo(int(fd), syscall.IPPROTO_IPV6, SO_ORIGINAL_DST)
if err != nil {
return err
}
destination = netip.AddrPortFrom(M.AddrFromIP(raw.Addr.Addr[:]), raw.Addr.Port)
2022-07-15 08:42:02 +08:00
}
2022-08-16 18:19:48 +08:00
return nil
})
return
2022-07-15 08:42:02 +08:00
}