2021-10-24 11:59:01 -04:00
|
|
|
package packetaddr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2021-11-20 18:24:21 -05:00
|
|
|
gonet "net"
|
2021-12-31 16:22:16 -05:00
|
|
|
|
|
|
|
"github.com/v2fly/v2ray-core/v5/common/buf"
|
|
|
|
"github.com/v2fly/v2ray-core/v5/common/net"
|
|
|
|
"github.com/v2fly/v2ray-core/v5/common/protocol"
|
2021-10-24 11:59:01 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
var addrParser = protocol.NewAddressParser(
|
|
|
|
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
|
|
|
|
protocol.AddressFamilyByte(0x02, net.AddressFamilyIPv6),
|
|
|
|
)
|
|
|
|
|
2021-12-30 10:12:32 -05:00
|
|
|
// AttachAddressToPacket
|
|
|
|
// relinquish ownership of data
|
|
|
|
// gain ownership of the returning value
|
|
|
|
func AttachAddressToPacket(data *buf.Buffer, address gonet.Addr) (*buf.Buffer, error) {
|
|
|
|
packetBuf := buf.New()
|
2021-11-20 18:24:21 -05:00
|
|
|
udpaddr := address.(*gonet.UDPAddr)
|
2021-10-24 11:59:01 -04:00
|
|
|
port, err := net.PortFromInt(uint32(udpaddr.Port))
|
|
|
|
if err != nil {
|
2021-12-30 10:12:32 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
err = addrParser.WriteAddressPort(packetBuf, net.IPAddress(udpaddr.IP), port)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-10-24 11:59:01 -04:00
|
|
|
}
|
2021-12-30 10:12:32 -05:00
|
|
|
_, err = packetBuf.Write(data.Bytes())
|
2021-10-24 11:59:01 -04:00
|
|
|
if err != nil {
|
2021-12-30 10:12:32 -05:00
|
|
|
return nil, err
|
2021-10-24 11:59:01 -04:00
|
|
|
}
|
2021-12-30 10:12:32 -05:00
|
|
|
data.Release()
|
|
|
|
return packetBuf, nil
|
2021-10-24 11:59:01 -04:00
|
|
|
}
|
|
|
|
|
2021-12-30 10:12:32 -05:00
|
|
|
// ExtractAddressFromPacket
|
|
|
|
// relinquish ownership of data
|
|
|
|
// gain ownership of the returning value
|
|
|
|
func ExtractAddressFromPacket(data *buf.Buffer) (*buf.Buffer, gonet.Addr, error) {
|
2021-10-24 11:59:01 -04:00
|
|
|
packetBuf := buf.StackNew()
|
2021-12-30 10:12:32 -05:00
|
|
|
address, port, err := addrParser.ReadAddressPort(&packetBuf, bytes.NewReader(data.Bytes()))
|
2021-10-24 11:59:01 -04:00
|
|
|
if err != nil {
|
2021-12-30 10:12:32 -05:00
|
|
|
return nil, nil, err
|
2021-10-24 11:59:01 -04:00
|
|
|
}
|
2021-12-31 16:22:16 -05:00
|
|
|
addr := &gonet.UDPAddr{
|
2021-10-24 11:59:01 -04:00
|
|
|
IP: address.IP(),
|
|
|
|
Port: int(port.Value()),
|
|
|
|
Zone: "",
|
|
|
|
}
|
2021-12-30 10:12:32 -05:00
|
|
|
data.Advance(packetBuf.Len())
|
2021-10-25 10:13:43 -04:00
|
|
|
packetBuf.Release()
|
2021-12-30 10:12:32 -05:00
|
|
|
return data, addr, nil
|
2021-10-24 11:59:01 -04:00
|
|
|
}
|