This commit is contained in:
RPRX 2020-11-25 19:01:53 +08:00
parent 47d23e9972
commit c7f7c08ead
711 changed files with 82154 additions and 2 deletions

View file

@ -0,0 +1,12 @@
package udp
import (
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/transport/internet"
)
func init() {
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
return new(Config)
}))
}

View file

@ -0,0 +1,145 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.14.0
// source: transport/internet/udp/config.proto
package udp
import (
proto "github.com/golang/protobuf/proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type Config struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *Config) Reset() {
*x = Config{}
if protoimpl.UnsafeEnabled {
mi := &file_transport_internet_udp_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_udp_config_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_transport_internet_udp_config_proto_rawDescGZIP(), []int{0}
}
var File_transport_internet_udp_config_proto protoreflect.FileDescriptor
var file_transport_internet_udp_config_proto_rawDesc = []byte{
0x0a, 0x23, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65,
0x72, 0x6e, 0x65, 0x74, 0x2f, 0x75, 0x64, 0x70, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1b, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e,
0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x75,
0x64, 0x70, 0x22, 0x08, 0x0a, 0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x76, 0x0a, 0x1f,
0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f,
0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x75, 0x64, 0x70, 0x50,
0x01, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x74,
0x6c, 0x73, 0x2f, 0x78, 0x72, 0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f,
0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e,
0x65, 0x74, 0x2f, 0x75, 0x64, 0x70, 0xaa, 0x02, 0x1b, 0x58, 0x72, 0x61, 0x79, 0x2e, 0x54, 0x72,
0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74,
0x2e, 0x55, 0x64, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_transport_internet_udp_config_proto_rawDescOnce sync.Once
file_transport_internet_udp_config_proto_rawDescData = file_transport_internet_udp_config_proto_rawDesc
)
func file_transport_internet_udp_config_proto_rawDescGZIP() []byte {
file_transport_internet_udp_config_proto_rawDescOnce.Do(func() {
file_transport_internet_udp_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_transport_internet_udp_config_proto_rawDescData)
})
return file_transport_internet_udp_config_proto_rawDescData
}
var file_transport_internet_udp_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_transport_internet_udp_config_proto_goTypes = []interface{}{
(*Config)(nil), // 0: xray.transport.internet.udp.Config
}
var file_transport_internet_udp_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_transport_internet_udp_config_proto_init() }
func file_transport_internet_udp_config_proto_init() {
if File_transport_internet_udp_config_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_transport_internet_udp_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Config); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_transport_internet_udp_config_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_transport_internet_udp_config_proto_goTypes,
DependencyIndexes: file_transport_internet_udp_config_proto_depIdxs,
MessageInfos: file_transport_internet_udp_config_proto_msgTypes,
}.Build()
File_transport_internet_udp_config_proto = out.File
file_transport_internet_udp_config_proto_rawDesc = nil
file_transport_internet_udp_config_proto_goTypes = nil
file_transport_internet_udp_config_proto_depIdxs = nil
}

View file

@ -0,0 +1,9 @@
syntax = "proto3";
package xray.transport.internet.udp;
option csharp_namespace = "Xray.Transport.Internet.Udp";
option go_package = "github.com/xtls/xray-core/v1/transport/internet/udp";
option java_package = "com.xray.transport.internet.udp";
option java_multiple_files = true;
message Config {}

View file

@ -0,0 +1,25 @@
package udp
import (
"context"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/net"
"github.com/xtls/xray-core/v1/transport/internet"
)
func init() {
common.Must(internet.RegisterTransportDialer(protocolName,
func(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
var sockopt *internet.SocketConfig
if streamSettings != nil {
sockopt = streamSettings.SocketSettings
}
conn, err := internet.DialSystem(ctx, dest, sockopt)
if err != nil {
return nil, err
}
// TODO: handle dialer options
return internet.Connection(conn), nil
}))
}

View file

@ -0,0 +1,198 @@
package udp
import (
"context"
"io"
"sync"
"time"
"github.com/xtls/xray-core/v1/common/signal/done"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/buf"
"github.com/xtls/xray-core/v1/common/net"
"github.com/xtls/xray-core/v1/common/protocol/udp"
"github.com/xtls/xray-core/v1/common/session"
"github.com/xtls/xray-core/v1/common/signal"
"github.com/xtls/xray-core/v1/features/routing"
"github.com/xtls/xray-core/v1/transport"
)
type ResponseCallback func(ctx context.Context, packet *udp.Packet)
type connEntry struct {
link *transport.Link
timer signal.ActivityUpdater
cancel context.CancelFunc
}
type Dispatcher struct {
sync.RWMutex
conns map[net.Destination]*connEntry
dispatcher routing.Dispatcher
callback ResponseCallback
}
func NewDispatcher(dispatcher routing.Dispatcher, callback ResponseCallback) *Dispatcher {
return &Dispatcher{
conns: make(map[net.Destination]*connEntry),
dispatcher: dispatcher,
callback: callback,
}
}
func (v *Dispatcher) RemoveRay(dest net.Destination) {
v.Lock()
defer v.Unlock()
if conn, found := v.conns[dest]; found {
common.Close(conn.link.Reader)
common.Close(conn.link.Writer)
delete(v.conns, dest)
}
}
func (v *Dispatcher) getInboundRay(ctx context.Context, dest net.Destination) *connEntry {
v.Lock()
defer v.Unlock()
if entry, found := v.conns[dest]; found {
return entry
}
newError("establishing new connection for ", dest).WriteToLog()
ctx, cancel := context.WithCancel(ctx)
removeRay := func() {
cancel()
v.RemoveRay(dest)
}
timer := signal.CancelAfterInactivity(ctx, removeRay, time.Second*4)
link, _ := v.dispatcher.Dispatch(ctx, dest)
entry := &connEntry{
link: link,
timer: timer,
cancel: removeRay,
}
v.conns[dest] = entry
go handleInput(ctx, entry, dest, v.callback)
return entry
}
func (v *Dispatcher) Dispatch(ctx context.Context, destination net.Destination, payload *buf.Buffer) {
// TODO: Add user to destString
newError("dispatch request to: ", destination).AtDebug().WriteToLog(session.ExportIDToError(ctx))
conn := v.getInboundRay(ctx, destination)
outputStream := conn.link.Writer
if outputStream != nil {
if err := outputStream.WriteMultiBuffer(buf.MultiBuffer{payload}); err != nil {
newError("failed to write first UDP payload").Base(err).WriteToLog(session.ExportIDToError(ctx))
conn.cancel()
return
}
}
}
func handleInput(ctx context.Context, conn *connEntry, dest net.Destination, callback ResponseCallback) {
defer conn.cancel()
input := conn.link.Reader
timer := conn.timer
for {
select {
case <-ctx.Done():
return
default:
}
mb, err := input.ReadMultiBuffer()
if err != nil {
newError("failed to handle UDP input").Base(err).WriteToLog(session.ExportIDToError(ctx))
return
}
timer.Update()
for _, b := range mb {
callback(ctx, &udp.Packet{
Payload: b,
Source: dest,
})
}
}
}
type dispatcherConn struct {
dispatcher *Dispatcher
cache chan *udp.Packet
done *done.Instance
}
func DialDispatcher(ctx context.Context, dispatcher routing.Dispatcher) (net.PacketConn, error) {
c := &dispatcherConn{
cache: make(chan *udp.Packet, 16),
done: done.New(),
}
d := NewDispatcher(dispatcher, c.callback)
c.dispatcher = d
return c, nil
}
func (c *dispatcherConn) callback(ctx context.Context, packet *udp.Packet) {
select {
case <-c.done.Wait():
packet.Payload.Release()
return
case c.cache <- packet:
default:
packet.Payload.Release()
return
}
}
func (c *dispatcherConn) ReadFrom(p []byte) (int, net.Addr, error) {
select {
case <-c.done.Wait():
return 0, nil, io.EOF
case packet := <-c.cache:
n := copy(p, packet.Payload.Bytes())
return n, &net.UDPAddr{
IP: packet.Source.Address.IP(),
Port: int(packet.Source.Port),
}, nil
}
}
func (c *dispatcherConn) WriteTo(p []byte, addr net.Addr) (int, error) {
buffer := buf.New()
raw := buffer.Extend(buf.Size)
n := copy(raw, p)
buffer.Resize(0, int32(n))
ctx := context.Background()
c.dispatcher.Dispatch(ctx, net.DestinationFromAddr(addr), buffer)
return n, nil
}
func (c *dispatcherConn) Close() error {
return c.done.Close()
}
func (c *dispatcherConn) LocalAddr() net.Addr {
return &net.UDPAddr{
IP: []byte{0, 0, 0, 0},
Port: 0,
}
}
func (c *dispatcherConn) SetDeadline(t time.Time) error {
return nil
}
func (c *dispatcherConn) SetReadDeadline(t time.Time) error {
return nil
}
func (c *dispatcherConn) SetWriteDeadline(t time.Time) error {
return nil
}

View file

@ -0,0 +1,86 @@
package udp_test
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/xtls/xray-core/v1/common"
"github.com/xtls/xray-core/v1/common/buf"
"github.com/xtls/xray-core/v1/common/net"
"github.com/xtls/xray-core/v1/common/protocol/udp"
"github.com/xtls/xray-core/v1/features/routing"
"github.com/xtls/xray-core/v1/transport"
. "github.com/xtls/xray-core/v1/transport/internet/udp"
"github.com/xtls/xray-core/v1/transport/pipe"
)
type TestDispatcher struct {
OnDispatch func(ctx context.Context, dest net.Destination) (*transport.Link, error)
}
func (d *TestDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
return d.OnDispatch(ctx, dest)
}
func (d *TestDispatcher) Start() error {
return nil
}
func (d *TestDispatcher) Close() error {
return nil
}
func (*TestDispatcher) Type() interface{} {
return routing.DispatcherType()
}
func TestSameDestinationDispatching(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
uplinkReader, uplinkWriter := pipe.New(pipe.WithSizeLimit(1024))
downlinkReader, downlinkWriter := pipe.New(pipe.WithSizeLimit(1024))
go func() {
for {
data, err := uplinkReader.ReadMultiBuffer()
if err != nil {
break
}
err = downlinkWriter.WriteMultiBuffer(data)
common.Must(err)
}
}()
var count uint32
td := &TestDispatcher{
OnDispatch: func(ctx context.Context, dest net.Destination) (*transport.Link, error) {
atomic.AddUint32(&count, 1)
return &transport.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
},
}
dest := net.UDPDestination(net.LocalHostIP, 53)
b := buf.New()
b.WriteString("abcd")
var msgCount uint32
dispatcher := NewDispatcher(td, func(ctx context.Context, packet *udp.Packet) {
atomic.AddUint32(&msgCount, 1)
})
dispatcher.Dispatch(ctx, dest, b)
for i := 0; i < 5; i++ {
dispatcher.Dispatch(ctx, dest, b)
}
time.Sleep(time.Second)
cancel()
if count != 1 {
t.Error("count: ", count)
}
if v := atomic.LoadUint32(&msgCount); v != 6 {
t.Error("msgCount: ", v)
}
}

View file

@ -0,0 +1,9 @@
package udp
import "github.com/xtls/xray-core/v1/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}

View file

@ -0,0 +1,132 @@
package udp
import (
"context"
"github.com/xtls/xray-core/v1/common/buf"
"github.com/xtls/xray-core/v1/common/net"
"github.com/xtls/xray-core/v1/common/protocol/udp"
"github.com/xtls/xray-core/v1/transport/internet"
)
type HubOption func(h *Hub)
func HubCapacity(capacity int) HubOption {
return func(h *Hub) {
h.capacity = capacity
}
}
func HubReceiveOriginalDestination(r bool) HubOption {
return func(h *Hub) {
h.recvOrigDest = r
}
}
type Hub struct {
conn *net.UDPConn
cache chan *udp.Packet
capacity int
recvOrigDest bool
}
func ListenUDP(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, options ...HubOption) (*Hub, error) {
hub := &Hub{
capacity: 256,
recvOrigDest: false,
}
for _, opt := range options {
opt(hub)
}
var sockopt *internet.SocketConfig
if streamSettings != nil {
sockopt = streamSettings.SocketSettings
}
if sockopt != nil && sockopt.ReceiveOriginalDestAddress {
hub.recvOrigDest = true
}
udpConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{
IP: address.IP(),
Port: int(port),
}, sockopt)
if err != nil {
return nil, err
}
newError("listening UDP on ", address, ":", port).WriteToLog()
hub.conn = udpConn.(*net.UDPConn)
hub.cache = make(chan *udp.Packet, hub.capacity)
go hub.start()
return hub, nil
}
// Close implements net.Listener.
func (h *Hub) Close() error {
h.conn.Close()
return nil
}
func (h *Hub) WriteTo(payload []byte, dest net.Destination) (int, error) {
return h.conn.WriteToUDP(payload, &net.UDPAddr{
IP: dest.Address.IP(),
Port: int(dest.Port),
})
}
func (h *Hub) start() {
c := h.cache
defer close(c)
oobBytes := make([]byte, 256)
for {
buffer := buf.New()
var noob int
var addr *net.UDPAddr
rawBytes := buffer.Extend(buf.Size)
n, noob, _, addr, err := ReadUDPMsg(h.conn, rawBytes, oobBytes)
if err != nil {
newError("failed to read UDP msg").Base(err).WriteToLog()
buffer.Release()
break
}
buffer.Resize(0, int32(n))
if buffer.IsEmpty() {
buffer.Release()
continue
}
payload := &udp.Packet{
Payload: buffer,
Source: net.UDPDestination(net.IPAddress(addr.IP), net.Port(addr.Port)),
}
if h.recvOrigDest && noob > 0 {
payload.Target = RetrieveOriginalDest(oobBytes[:noob])
if payload.Target.IsValid() {
newError("UDP original destination: ", payload.Target).AtDebug().WriteToLog()
} else {
newError("failed to read UDP original destination").WriteToLog()
}
}
select {
case c <- payload:
default:
buffer.Release()
payload.Payload = nil
}
}
}
// Addr implements net.Listener.
func (h *Hub) Addr() net.Addr {
return h.conn.LocalAddr()
}
func (h *Hub) Receive() <-chan *udp.Packet {
return h.cache
}

View file

@ -0,0 +1,37 @@
// +build freebsd
package udp
import (
"bytes"
"encoding/gob"
"io"
"github.com/xtls/xray-core/v1/common/net"
"github.com/xtls/xray-core/v1/transport/internet"
)
// RetrieveOriginalDest from stored laddr, caddr
func RetrieveOriginalDest(oob []byte) net.Destination {
dec := gob.NewDecoder(bytes.NewBuffer(oob))
var la, ra net.UDPAddr
dec.Decode(&la)
dec.Decode(&ra)
ip, port, err := internet.OriginalDst(&la, &ra)
if err != nil {
return net.Destination{}
}
return net.UDPDestination(net.IPAddress(ip), net.Port(port))
}
// ReadUDPMsg stores laddr, caddr for later use
func ReadUDPMsg(conn *net.UDPConn, payload []byte, oob []byte) (int, int, int, *net.UDPAddr, error) {
nBytes, addr, err := conn.ReadFromUDP(payload)
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
enc.Encode(conn.LocalAddr().(*net.UDPAddr))
enc.Encode(addr)
var reader io.Reader = &buf
noob, _ := reader.Read(oob)
return nBytes, noob, 0, addr, err
}

View file

@ -0,0 +1,33 @@
// +build linux
package udp
import (
"syscall"
"github.com/xtls/xray-core/v1/common/net"
"golang.org/x/sys/unix"
)
func RetrieveOriginalDest(oob []byte) net.Destination {
msgs, err := syscall.ParseSocketControlMessage(oob)
if err != nil {
return net.Destination{}
}
for _, msg := range msgs {
if msg.Header.Level == syscall.SOL_IP && msg.Header.Type == syscall.IP_RECVORIGDSTADDR {
ip := net.IPAddress(msg.Data[4:8])
port := net.PortFromBytes(msg.Data[2:4])
return net.UDPDestination(ip, port)
} else if msg.Header.Level == syscall.SOL_IPV6 && msg.Header.Type == unix.IPV6_RECVORIGDSTADDR {
ip := net.IPAddress(msg.Data[8:24])
port := net.PortFromBytes(msg.Data[2:4])
return net.UDPDestination(ip, port)
}
}
return net.Destination{}
}
func ReadUDPMsg(conn *net.UDPConn, payload []byte, oob []byte) (int, int, int, *net.UDPAddr, error) {
return conn.ReadMsgUDP(payload, oob)
}

View file

@ -0,0 +1,16 @@
// +build !linux,!freebsd
package udp
import (
"github.com/xtls/xray-core/v1/common/net"
)
func RetrieveOriginalDest(oob []byte) net.Destination {
return net.Destination{}
}
func ReadUDPMsg(conn *net.UDPConn, payload []byte, oob []byte) (int, int, int, *net.UDPAddr, error) {
nBytes, addr, err := conn.ReadFromUDP(payload)
return nBytes, 0, 0, addr, err
}

View file

@ -0,0 +1,5 @@
package udp
//go:generate go run github.com/xtls/xray-core/v1/common/errors/errorgen
const protocolName = "udp"