package socket

import (
	
	
	
	
	

	
	
)

// maxDatagramSize bounds a single read from the UDP socket. QUIC packets never
// exceed this; larger reads would be truncated by quic-go anyway.
const maxDatagramSize = 1452 + 512 // generous: max QUIC packet plus headroom

var ipRecvPool = make(chan []byte, 1024)

// IpTransport is the direct-UDP transport: it reads datagrams from a
// net.PacketConn and forwards them to the [MagicConn]'s recv channel, and sends
// datagrams the magic socket routes to it. It is the Go analog of the Rust
// IpTransport (iroh/src/socket/transports/ip.rs).
//
// Create one with [NewIpTransport] and start its recv loop with [IpTransport.Serve].
type IpTransport struct {
	conn   *net.UDPConn
	recvCh chan<- recvBatch

	// gro is set when the kernel coalesces received datagrams for this
	// socket; the receive loop then reads runs rather than datagrams.
	gro bool

	// pktinfo is set when the socket is bound to the unspecified address and
	// the platform delivers the destination address of received datagrams.
	// A wildcard socket has no fixed source address: the kernel picks one per
	// reply by route, which on a multi-homed host, or one whose peer is
	// reached over a bridge or a container network, need not be the address
	// the peer sent to. A QUIC peer then receives packets from an address it
	// never dialed and fails path validation. The transport records the local
	// address each remote last reached and answers from it, as quinn does
	// for the Rust iroh through quinn-udp's RecvMeta::dst_ip and
	// Transmit::src_ip.
	pktinfo bool
	localMu sync.Mutex
	local   map[netip.AddrPort]*localEntry
	// heard orders entries by the last datagram heard from each remote,
	// circularly through this sentinel: heard.next is newest, heard.prev
	// oldest and first to be evicted.
	heard localEntry
}

// localAddr is the local address a remote's datagrams arrive at.
type localAddr struct {
	addr    netip.Addr
	ifIndex int
}

// localEntry is a remote's entry in the arrival-address table. cmsg is the
// packet-info message that makes a reply leave from the address; it is
// shared with senders and never written after it is built.
type localEntry struct {
	remote netip.AddrPort
	localAddr
	cmsg       []byte
	prev, next *localEntry
}

// maxLocalAddrs bounds the arrival-address table. A full table drops the
// remote heard from longest ago; a reply to a peer not in the table leaves
// from the address the kernel picks, as before the table.
const maxLocalAddrs = 4096

// groBufSize bounds one UDP_GRO read: the kernel coalesces at most a 64 KiB
// run of datagrams into a single recvmsg. It is a correctness bound, not a
// tuning knob -- a read buffer shorter than the run the kernel assembled
// takes the head of the run and discards the rest, which the peer sees as
// loss. TestIpTransportGROReadsAFullRun holds the floor.
const groBufSize = 65535

var groRecvPool = sync.Pool{New: func() any {  := make([]byte, groBufSize); return & }}

// NewIpTransport returns an IpTransport over conn that delivers received
// datagrams to recvCh. The transport does not take ownership of conn; the caller
// closes it.
func ( *net.UDPConn,  chan<- recvBatch) *IpTransport {
	 := &IpTransport{conn: , recvCh: , gro: enableGRO()}
	if ,  := .LocalAddr().(*net.UDPAddr);  && .IP.IsUnspecified() {
		.pktinfo = enablePacketInfo()
		if .pktinfo {
			.local = make(map[netip.AddrPort]*localEntry)
			.heard.prev, .heard.next = &.heard, &.heard
		}
	}
	return 
}

// enablePacketInfo asks the kernel for the destination address of received
// datagrams. Either family may fail: an IPv4 socket has no IPv6 options, and
// some platforms have neither. It reports whether at least one family took.
func enablePacketInfo( *net.UDPConn) bool {
	 := ipv4.NewPacketConn().SetControlMessage(ipv4.FlagDst|ipv4.FlagInterface, true) == nil
	 := ipv6.NewPacketConn().SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true) == nil
	return  || 
}

// recordLocal notes the local address remote's datagram arrived at.
func ( *IpTransport) ( netip.AddrPort,  []byte) {
	if ,  := parsePacketInfo();  {
		.record(, )
	}
}

// record notes la as remote's arrival address and remote as the most
// recently heard. The control message is rebuilt only when la changes.
func ( *IpTransport) ( netip.AddrPort,  localAddr) {
	.localMu.Lock()
	defer .localMu.Unlock()
	if ,  := .local[];  {
		if .localAddr !=  {
			.localAddr = 
			.cmsg = packetInfoMessage(, )
		}
		.unlink()
		.linkFront()
		return
	}
	if len(.local) >= maxLocalAddrs {
		 := .heard.prev
		.unlink()
		delete(.local, .remote)
	}
	 := &localEntry{remote: , localAddr: , cmsg: packetInfoMessage(, )}
	.local[] = 
	.linkFront()
}

// linkFront puts e at the head of the recency list. Caller holds localMu.
func ( *IpTransport) ( *localEntry) {
	.prev, .next = &.heard, .heard.next
	.prev.next, .next.prev = , 
}

// unlink removes e from the recency list. Caller holds localMu.
func ( *IpTransport) ( *localEntry) {
	.prev.next, .next.prev = .next, .prev
	.prev, .next = nil, nil
}

// forgetLocal drops remote's arrival address after the kernel refused it.
func ( *IpTransport) ( netip.AddrPort) {
	.localMu.Lock()
	if ,  := .local[];  {
		.unlink()
		delete(.local, )
	}
	.localMu.Unlock()
}

// packetInfoFor returns the control message that makes a datagram to remote
// leave from the address remote last reached, or nil when none is known. The
// message is shared and must not be modified.
func ( *IpTransport) ( netip.AddrPort) []byte {
	if !.pktinfo {
		return nil
	}
	var  []byte
	.localMu.Lock()
	if ,  := .local[];  {
		 = .cmsg
	}
	.localMu.Unlock()
	return 
}

// packetInfoMessage builds the packet-info control message naming la as the
// source of datagrams to remote, or nil when it cannot be. The source must
// be of the destination's family: IPv4 traffic on a dual-stack socket
// carries IP-level control messages in both directions, so an IPv4 remote
// gets an IPv4 message whatever the socket.
func packetInfoMessage( netip.AddrPort,  localAddr) []byte {
	if .Addr().Is4() {
		if !.addr.Is4() {
			return nil
		}
		return (&ipv4.ControlMessage{Src: .addr.AsSlice()}).Marshal()
	}
	if !.addr.Is6() || .addr.Is4In6() {
		return nil
	}
	return (&ipv6.ControlMessage{Src: .addr.AsSlice(), IfIndex: .ifIndex}).Marshal()
}

// maxControlSize bounds the control messages read with a datagram: a
// packet-info message of either family plus headroom.
const maxControlSize = 128

// LocalAddr returns the bound local address of the underlying socket.
func ( *IpTransport) () net.Addr { return .conn.LocalAddr() }

// Serve runs the receive loop until ctx is cancelled or the socket is closed.
// Each datagram is delivered to the recv channel tagged with its real remote IP
// address (canonicalized: an IPv4-mapped IPv6 source becomes plain IPv4, to
// match iroh/src/socket/transports/ip.rs:221 to_canonical). Empty datagrams and
// transient errors are skipped; a closed socket ends the loop cleanly.
func ( *IpTransport) ( context.Context) {
	if .gro {
		.serveGRO()
		return
	}
	var  []byte
	if .pktinfo {
		 = make([]byte, maxControlSize)
	}
	for {
		if .Err() != nil {
			return
		}
		 := getIPRecvBuffer()
		var (
			,  int
			      netip.AddrPort
			     error
		)
		if .pktinfo {
			, , _, ,  = .conn.ReadMsgUDPAddrPort(, )
		} else {
			, ,  = .conn.ReadFromUDPAddrPort()
		}
		if  != nil {
			putIPRecvBuffer()
			if errors.Is(, net.ErrClosed) || .Err() != nil {
				return
			}
			// Transient read error (e.g. ICMP-driven recv error on some
			// platforms): keep serving.
			continue
		}
		if  == 0 {
			putIPRecvBuffer()
			// Timeout or platform quirk; nothing to deliver.
			continue
		}
		recordUDPReceive(1, false)
		// The transport address is internal to iroh and is always the canonical
		// (unmapped) form. iroh/src/socket/transports/ip.rs:219.
		 := canonicalAddrPort()
		if .pktinfo {
			.recordLocal(, [:])
		}
		 := recvBatch{data: [:], ip: , releaseIP: true}
		if !.enqueue(, ) {
			return
		}
	}
}

// serveGRO is the receive loop for a socket with UDP_GRO enabled: one read can
// return a run of equally sized datagrams from the same peer, so it queues the
// whole read as one batch strided by the segment size the kernel reports and
// hands the buffer back to the pool once ReadFrom has copied out the last
// segment.
func ( *IpTransport) ( context.Context) {
	// The read carries the segment size and, on a wildcard socket, the
	// packet-info message too: room for both, not just the one.
	var  [groOOBSize + maxControlSize]byte
	for {
		if .Err() != nil {
			return
		}
		 := groRecvPool.Get().(*[]byte)
		 := *
		, , , ,  := .conn.ReadMsgUDPAddrPort(, [:])
		if  != nil {
			groRecvPool.Put()
			if errors.Is(, net.ErrClosed) || .Err() != nil {
				return
			}
			continue
		}
		if  == 0 {
			groRecvPool.Put()
			continue
		}
		 := groSegmentSize([:])
		if  <= 0 ||  >  {
			 = 
		}
		recordUDPReceive((+-1)/,  < )
		 := canonicalAddrPort()
		if .pktinfo {
			// A coalesced run is one peer's, so one arrival address
			// covers every datagram in it.
			.recordLocal(, [:])
		}
		 := recvBatch{data: [:], stride: , ip: , groBuf: }
		if !.enqueue(, ) {
			return
		}
	}
}

func ( *IpTransport) ( context.Context,  recvBatch) bool {
	select {
	case .recvCh <- :
		return true
	default:
	}
	select {
	case .recvCh <- :
		return true
	case <-.Done():
		.release()
		return false
	}
}

func getIPRecvBuffer() []byte {
	select {
	case  := <-ipRecvPool:
		return 
	default:
		return make([]byte, maxDatagramSize)
	}
}

func putIPRecvBuffer( []byte) {
	if cap() != maxDatagramSize {
		return
	}
	select {
	case ipRecvPool <- [:maxDatagramSize]:
	default:
	}
}

// send writes p to the IP destination dst. The destination is canonicalized so
// an IPv4-mapped IPv6 address is sent as plain IPv4, matching
// iroh/src/socket/transports/ip.rs:310 canonical_addr. When dst has reached
// this socket before, the datagram leaves from the address it arrived at. It
// reports the number of bytes written.
func ( *IpTransport) ( []byte,  netip.AddrPort) (int, error) {
	 = canonicalAddrPort()
	if  := .packetInfoFor();  != nil {
		, ,  := .conn.WriteMsgUDPAddrPort(, , )
		if  == nil {
			return , nil
		}
		// The kernel refused the source (an address that has since gone,
		// or a platform quirk): fall back to its own choice, and stop asking
		// until the peer reaches us again.
		.forgetLocal()
	}
	,  := .conn.WriteToUDPAddrPort(, )
	return , 
}

// withPacketInfo prepends the packet-info control message for dst, when one
// is known, to oob. The result is built in buf, grown if too small; oob and
// the shared message are not written to.
func ( *IpTransport) ( netip.AddrPort, ,  []byte) []byte {
	 := .packetInfoFor()
	if  == nil {
		return 
	}
	 = append([:0], ...)
	return append(, ...)
}

func canonicalAddrPort( netip.AddrPort) netip.AddrPort {
	 := .Addr()
	if !.Is4In6() {
		return 
	}
	return netip.AddrPortFrom(.Unmap(), .Port())
}

func udpAddrFromAddrPort( netip.AddrPort) *net.UDPAddr {
	return net.UDPAddrFromAddrPort(canonicalAddrPort())
}

func addrPortFromUDPAddr( *net.UDPAddr) netip.AddrPort {
	return canonicalAddrPort(.AddrPort())
}

// addrPort extracts a netip.AddrPort from a net.Addr, handling the *net.UDPAddr
// that net.PacketConn.ReadFrom returns as well as anything already carrying an
// AddrPort.
func addrPort( net.Addr) (netip.AddrPort, bool) {
	switch v := .(type) {
	case *net.UDPAddr:
		return addrPortFromUDPAddr(), true
	case interface{ () netip.AddrPort }:
		return canonicalAddrPort(.()), true
	default:
		,  := netip.ParseAddrPort(.String())
		if  != nil {
			return netip.AddrPort{}, false
		}
		return canonicalAddrPort(), true
	}
}