From c5aeee39ad5cc62980f2835ba541d8e6b4187edd Mon Sep 17 00:00:00 2001 From: Sudarshan Reddy Date: Sat, 18 Sep 2021 21:05:26 +0100 Subject: [PATCH] use x/net/ipv{4,6} to construct oob info when writing packets (#3278) --- conn_oob.go | 49 +++++++++---------------------------------------- 1 file changed, 9 insertions(+), 40 deletions(-) diff --git a/conn_oob.go b/conn_oob.go index 0d55d57b..b4678137 100644 --- a/conn_oob.go +++ b/conn_oob.go @@ -8,10 +8,8 @@ import ( "errors" "fmt" "net" - "runtime" "syscall" "time" - "unsafe" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" @@ -239,50 +237,21 @@ func (info *packetInfo) OOB() []byte { // struct in_addr ipi_spec_dst; /* Local address */ // struct in_addr ipi_addr; /* Header Destination address */ // }; - msgLen := 12 - if runtime.GOOS == "freebsd" { - msgLen = 4 + cm := ipv4.ControlMessage{ + Src: ip4, + IfIndex: int(info.ifIndex), } - cmsglen := cmsgLen(msgLen) - oob := make([]byte, cmsglen) - cmsg := (*syscall.Cmsghdr)(unsafe.Pointer(&oob[0])) - cmsg.Level = syscall.IPPROTO_TCP - cmsg.Type = msgTypeIPv4PKTINFO - cmsg.SetLen(cmsglen) - off := cmsgLen(0) - if runtime.GOOS != "freebsd" { - // FreeBSD does not support in_pktinfo, just an in_addr is sent - binary.LittleEndian.PutUint32(oob[off:], info.ifIndex) - off += 4 - } - copy(oob[off:], ip4) - return oob + return cm.Marshal() } else if len(info.addr) == 16 { // struct in6_pktinfo { // struct in6_addr ipi6_addr; /* src/dst IPv6 address */ // unsigned int ipi6_ifindex; /* send/recv interface index */ // }; - const msgLen = 20 - cmsglen := cmsgLen(msgLen) - oob := make([]byte, cmsglen) - cmsg := (*syscall.Cmsghdr)(unsafe.Pointer(&oob[0])) - cmsg.Level = syscall.IPPROTO_IPV6 - cmsg.Type = msgTypeIPv6PKTINFO - cmsg.SetLen(cmsglen) - off := cmsgLen(0) - off += copy(oob[off:], info.addr) - binary.LittleEndian.PutUint32(oob[off:], info.ifIndex) - return oob + cm := ipv6.ControlMessage{ + Src: info.addr, + IfIndex: int(info.ifIndex), + } + return cm.Marshal() } return nil } - -func cmsgLen(datalen int) int { - return cmsgAlign(syscall.SizeofCmsghdr) + datalen -} - -func cmsgAlign(salen int) int { - const sizeOfPtr = 0x8 - salign := sizeOfPtr - return (salen + salign - 1) & ^(salign - 1) -}