//go:build linux

package socket

import (
	
	
	
	

	
)

// WriteMsgUDP writes a possibly segmented datagram. Direct IP destinations use
// the kernel's UDP_SEGMENT path. Other transports receive one datagram per
// segment through the ordinary magic-socket router.
func ( *MagicConn) (,  []byte,  *net.UDPAddr) (,  int,  error) {
	 := udpSegmentSize()
	if .sock.IsClosed() {
		return len(), len(), nil
	}
	 := canonicalAddrPort(.AddrPort())
	if .transports.ip == nil || (!isDefinitelyIP(.Addr()) && Classify(.Addr()) != KindIP) {
		.writeMsgSegments(, , )
		return len(), len(), nil
	}
	// Stack buffer for the packet-info message: no allocation per send.
	var  [maxControlSize]byte
	 := .transports.ip.withPacketInfo(, , [:0])
	, ,  = .udp.WriteMsgUDPAddrPort(, , )
	if  != nil && len() > len() && !gsoRefused(, ) {
		// The kernel refused the source: the address it names has gone, or
		// the platform will not take it. Drop it and let the kernel choose,
		// as IpTransport.send does. Without this the entry outlives the
		// address and every later send to this peer is refused the same way.
		.transports.ip.forgetLocal()
		, ,  = .udp.WriteMsgUDPAddrPort(, , )
	}
	if  == nil {
		for range segmentCount(len(), ) {
			.recordIPSent()
		}
		return , len(), nil
	}
	// EIO on a segmented write is the kernel refusing GSO, not a lost
	// datagram: the caller disables GSO and resends the batch one datagram at
	// a time, and those resends are counted on the ordinary path. Counting
	// here would count them twice.
	if gsoRefused(, ) {
		return , , 
	}
	.metrics.blackholed.Add(uint64(segmentCount(len(), )))
	return len(), len(), nil
}

// gsoRefused reports whether err is the kernel declining to segment a write
// rather than a fault in the datagram or its source address.
func gsoRefused( error,  int) bool {
	return  > 0 && errors.Is(, unix.EIO)
}

func ( *MagicConn) ( []byte,  *net.UDPAddr,  int) {
	if  <= 0 ||  >= len() {
		.WriteTo(, )
		return
	}
	if .sendRelayBatch(canonicalAddrPort(.AddrPort()).Addr(), , ) {
		return
	}
	for len() > 0 {
		 := min(len(), )
		.WriteTo([:], )
		 = [:]
	}
}

func udpSegmentSize( []byte) int {
	for len() > 0 {
		, , ,  := unix.ParseOneSocketControlMessage()
		if  != nil {
			return 0
		}
		if .Level == syscall.IPPROTO_UDP && .Type == unix.UDP_SEGMENT && len() >= 2 {
			return int(binary.NativeEndian.Uint16())
		}
		 = 
	}
	return 0
}