2023-05-11 19:01:41 +08:00
|
|
|
package packet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2023-11-03 21:01:45 +08:00
|
|
|
"github.com/metacubex/mihomo/common/pool"
|
2023-05-11 19:01:41 +08:00
|
|
|
)
|
|
|
|
|
2023-05-19 23:29:43 +08:00
|
|
|
type WaitReadFrom interface {
|
|
|
|
WaitReadFrom() (data []byte, put func(), addr net.Addr, err error)
|
|
|
|
}
|
|
|
|
|
2023-05-11 19:01:41 +08:00
|
|
|
type EnhancePacketConn interface {
|
|
|
|
net.PacketConn
|
2023-05-19 23:29:43 +08:00
|
|
|
WaitReadFrom
|
2023-05-11 19:01:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewEnhancePacketConn(pc net.PacketConn) EnhancePacketConn {
|
|
|
|
if udpConn, isUDPConn := pc.(*net.UDPConn); isUDPConn {
|
|
|
|
return &enhanceUDPConn{UDPConn: udpConn}
|
|
|
|
}
|
|
|
|
if enhancePC, isEnhancePC := pc.(EnhancePacketConn); isEnhancePC {
|
|
|
|
return enhancePC
|
|
|
|
}
|
2023-05-15 22:45:08 +08:00
|
|
|
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
|
|
|
return newEnhanceSingPacketConn(singPC)
|
|
|
|
}
|
2023-05-11 19:01:41 +08:00
|
|
|
return &enhancePacketConn{PacketConn: pc}
|
|
|
|
}
|
|
|
|
|
|
|
|
type enhancePacketConn struct {
|
|
|
|
net.PacketConn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
|
|
return waitReadFrom(c.PacketConn)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhancePacketConn) Upstream() any {
|
|
|
|
return c.PacketConn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhancePacketConn) WriterReplaceable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhancePacketConn) ReaderReplaceable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhanceUDPConn) Upstream() any {
|
|
|
|
return c.UDPConn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhanceUDPConn) WriterReplaceable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *enhanceUDPConn) ReaderReplaceable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func waitReadFrom(pc net.PacketConn) (data []byte, put func(), addr net.Addr, err error) {
|
|
|
|
readBuf := pool.Get(pool.UDPBufferSize)
|
|
|
|
put = func() {
|
|
|
|
_ = pool.Put(readBuf)
|
|
|
|
}
|
|
|
|
var readN int
|
|
|
|
readN, addr, err = pc.ReadFrom(readBuf)
|
|
|
|
if readN > 0 {
|
|
|
|
data = readBuf[:readN]
|
|
|
|
} else {
|
|
|
|
put()
|
|
|
|
put = nil
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|