2020-10-02 19:09:12 +08:00
|
|
|
package vless
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
|
2022-01-08 15:05:55 +08:00
|
|
|
"github.com/nadoo/glider/pkg/pool"
|
2020-10-02 19:09:12 +08:00
|
|
|
)
|
|
|
|
|
2020-10-03 20:51:27 +08:00
|
|
|
// PktConn is a udp Packet.Conn.
|
|
|
|
type PktConn struct{ net.Conn }
|
2020-10-02 19:09:12 +08:00
|
|
|
|
|
|
|
// NewPktConn returns a PktConn.
|
2020-10-03 20:51:27 +08:00
|
|
|
func NewPktConn(c net.Conn) *PktConn { return &PktConn{Conn: c} }
|
2020-10-02 19:09:12 +08:00
|
|
|
|
|
|
|
// ReadFrom implements the necessary function of net.PacketConn.
|
2022-02-26 22:32:11 +08:00
|
|
|
// TODO: we know that we use it in proxy.CopyUDP and the length of b is enough, check it later.
|
2020-10-02 19:09:12 +08:00
|
|
|
func (pc *PktConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
2020-10-15 00:19:05 +08:00
|
|
|
if len(b) < 2 {
|
|
|
|
return 0, nil, errors.New("buf size is not enough")
|
|
|
|
}
|
|
|
|
|
2020-10-02 19:09:12 +08:00
|
|
|
// Length
|
|
|
|
if _, err := io.ReadFull(pc.Conn, b[:2]); err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
|
|
|
length := int(binary.BigEndian.Uint16(b[:2]))
|
|
|
|
|
|
|
|
if len(b) < length {
|
|
|
|
return 0, nil, errors.New("buf size is not enough")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Payload
|
|
|
|
n, err := io.ReadFull(pc.Conn, b[:length])
|
2020-10-10 19:04:33 +08:00
|
|
|
return n, nil, err
|
2020-10-02 19:09:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// WriteTo implements the necessary function of net.PacketConn.
|
|
|
|
func (pc *PktConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
2020-11-03 22:52:50 +08:00
|
|
|
buf := pool.GetBytesBuffer()
|
|
|
|
defer pool.PutBytesBuffer(buf)
|
2020-10-02 19:09:12 +08:00
|
|
|
|
|
|
|
binary.Write(buf, binary.BigEndian, uint16(len(b)))
|
|
|
|
buf.Write(b)
|
|
|
|
|
2020-10-15 00:19:05 +08:00
|
|
|
n, err := pc.Write(buf.Bytes())
|
|
|
|
if n > 2 {
|
|
|
|
return n - 2, err
|
|
|
|
}
|
|
|
|
return 0, err
|
2020-10-02 19:09:12 +08:00
|
|
|
}
|