| 1 |
//go:build !windows |
| 2 |
|
| 3 |
package dns |
| 4 |
|
| 5 |
import ( |
| 6 |
"net" |
| 7 |
|
| 8 |
"golang.org/x/net/ipv4" |
| 9 |
"golang.org/x/net/ipv6" |
| 10 |
) |
| 11 |
|
| 12 |
var minOOB4Size, minOOB6Size = func() (int, int) { |
| 13 |
oob4 := ipv4.NewControlMessage(ipv4.FlagDst | ipv4.FlagInterface) |
| 14 |
oob6 := ipv6.NewControlMessage(ipv6.FlagDst | ipv6.FlagInterface) |
| 15 |
return len(oob4), len(oob6) |
| 16 |
}() |
| 17 |
|
| 18 |
// Size return the size of the oob buffer that should be used. |
| 19 |
// |
| 20 |
// We can't know whether we'll get an IPv4 control message or an |
| 21 |
// IPv6 control message ahead of time. To get around this, we size |
| 22 |
// the buffer equal to the largest of the two. |
| 23 |
var oobSize = max(minOOB4Size, minOOB6Size) |
| 24 |
|
| 25 |
// parseFromOOB takes oob data and returns the destination IP. |
| 26 |
func parseFromOOB(oob []byte) net.IP { |
| 27 |
// Start with IPv6 and then fallback to IPv4 |
| 28 |
// TODO(fastest963): Figure out a way to prefer one or the other. Looking at |
| 29 |
// the lvl of the header for a 0 or 41 isn't cross-platform. |
| 30 |
if len(oob) >= minOOB6Size { |
| 31 |
cm6 := new(ipv6.ControlMessage) |
| 32 |
if cm6.Parse(oob) == nil && cm6.Dst != nil { |
| 33 |
return cm6.Dst |
| 34 |
} |
| 35 |
} |
| 36 |
if len(oob) >= minOOB4Size { |
| 37 |
cm4 := new(ipv4.ControlMessage) |
| 38 |
if cm4.Parse(oob) == nil && cm4.Dst != nil { |
| 39 |
return cm4.Dst |
| 40 |
} |
| 41 |
} |
| 42 |
return nil |
| 43 |
} |
| 44 |
|
| 45 |
// sourceFromOOB takes oob data and returns new oob data with the Src equal to the Dst |
| 46 |
func sourceFromOOB(oob []byte) []byte { |
| 47 |
dst := parseFromOOB(oob) |
| 48 |
if dst == nil { |
| 49 |
return nil |
| 50 |
} |
| 51 |
// If the dst is definitely an IPv6, then use ipv6's ControlMessage to |
| 52 |
// respond otherwise use ipv4's because ipv6's marshal ignores ipv4 |
| 53 |
// addresses. |
| 54 |
if dst.To4() == nil { |
| 55 |
cm := new(ipv6.ControlMessage) |
| 56 |
cm.Src = dst |
| 57 |
oob = cm.Marshal() |
| 58 |
} else { |
| 59 |
cm := new(ipv4.ControlMessage) |
| 60 |
cm.Src = dst |
| 61 |
oob = cm.Marshal() |
| 62 |
} |
| 63 |
return oob |
| 64 |
} |