2020-07-22 23:02:15 +08:00
|
|
|
package protocol
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2023-11-03 21:01:45 +08:00
|
|
|
N "github.com/metacubex/mihomo/common/net"
|
|
|
|
"github.com/metacubex/mihomo/common/pool"
|
2020-07-22 23:02:15 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type PacketConn struct {
|
2023-05-28 22:51:26 +08:00
|
|
|
N.EnhancePacketConn
|
2020-07-22 23:02:15 +08:00
|
|
|
Protocol
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
2021-09-20 21:02:18 +08:00
|
|
|
buf := pool.GetBuffer()
|
|
|
|
defer pool.PutBuffer(buf)
|
2021-02-15 14:32:03 +08:00
|
|
|
err := c.EncodePacket(buf, b)
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2023-05-28 22:51:26 +08:00
|
|
|
_, err = c.EnhancePacketConn.WriteTo(buf.Bytes(), addr)
|
2020-07-22 23:02:15 +08:00
|
|
|
return len(b), err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
2023-05-28 22:51:26 +08:00
|
|
|
n, addr, err := c.EnhancePacketConn.ReadFrom(b)
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return n, addr, err
|
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
decoded, err := c.DecodePacket(b[:n])
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return n, addr, err
|
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
copy(b, decoded)
|
|
|
|
return len(decoded), addr, nil
|
2020-07-22 23:02:15 +08:00
|
|
|
}
|
2023-05-28 22:51:26 +08:00
|
|
|
|
|
|
|
func (c *PacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
|
|
data, put, addr, err = c.EnhancePacketConn.WaitReadFrom()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
data, err = c.DecodePacket(data)
|
|
|
|
if err != nil {
|
|
|
|
if put != nil {
|
|
|
|
put()
|
|
|
|
}
|
|
|
|
data = nil
|
|
|
|
put = nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|