mirror of
https://github.com/SagerNet/sing.git
synced 2025-04-04 20:37:40 +03:00
44 lines
932 B
Go
44 lines
932 B
Go
package bufio
|
|
|
|
import (
|
|
"net"
|
|
|
|
"github.com/sagernet/sing/common/buf"
|
|
M "github.com/sagernet/sing/common/metadata"
|
|
N "github.com/sagernet/sing/common/network"
|
|
)
|
|
|
|
var _ N.NetPacketConn = (*FallbackPacketConn)(nil)
|
|
|
|
type FallbackPacketConn struct {
|
|
N.PacketConn
|
|
}
|
|
|
|
func NewNetPacketConn(conn N.PacketConn) N.NetPacketConn {
|
|
if packetConn, loaded := conn.(N.NetPacketConn); loaded {
|
|
return packetConn
|
|
}
|
|
return &FallbackPacketConn{PacketConn: conn}
|
|
}
|
|
|
|
func (c *FallbackPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
buffer := buf.With(p)
|
|
destination, err := c.ReadPacket(buffer)
|
|
if err != nil {
|
|
return
|
|
}
|
|
n = buffer.Len()
|
|
if buffer.Start() > 0 {
|
|
copy(p, buffer.Bytes())
|
|
}
|
|
addr = destination.UDPAddr()
|
|
return
|
|
}
|
|
|
|
func (c *FallbackPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
err = c.WritePacket(buf.As(p), M.SocksaddrFromNet(addr))
|
|
if err == nil {
|
|
n = len(p)
|
|
}
|
|
return
|
|
}
|