2020-07-22 23:02:15 +08:00
|
|
|
package protocol
|
|
|
|
|
|
|
|
import (
|
2021-02-15 14:32:03 +08:00
|
|
|
"bytes"
|
2020-07-22 23:02:15 +08:00
|
|
|
"net"
|
|
|
|
|
2021-05-13 22:18:49 +08:00
|
|
|
"github.com/Dreamacro/clash/transport/ssr/tools"
|
2020-07-22 23:02:15 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type PacketConn struct {
|
|
|
|
net.PacketConn
|
|
|
|
Protocol
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
2021-02-15 14:32:03 +08:00
|
|
|
buf := tools.BufPool.Get().(*bytes.Buffer)
|
|
|
|
defer tools.BufPool.Put(buf)
|
|
|
|
defer buf.Reset()
|
|
|
|
err := c.EncodePacket(buf, b)
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
_, err = c.PacketConn.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) {
|
|
|
|
n, addr, err := c.PacketConn.ReadFrom(b)
|
|
|
|
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
|
|
|
}
|