github.com/imannamdari/v2ray-core/v5@v5.0.5/transport/internet/udp/dispatcher_packetaddr.go (about)

     1  package udp
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/imannamdari/v2ray-core/v5/common/buf"
     7  	"github.com/imannamdari/v2ray-core/v5/common/net"
     8  	"github.com/imannamdari/v2ray-core/v5/common/net/packetaddr"
     9  	"github.com/imannamdari/v2ray-core/v5/common/protocol/udp"
    10  	"github.com/imannamdari/v2ray-core/v5/features/routing"
    11  )
    12  
    13  type PacketAddrDispatcher struct {
    14  	conn     net.PacketConn
    15  	callback ResponseCallback
    16  	ctx      context.Context
    17  }
    18  
    19  func (p PacketAddrDispatcher) Close() error {
    20  	return p.conn.Close()
    21  }
    22  
    23  func (p PacketAddrDispatcher) Dispatch(ctx context.Context, destination net.Destination, payload *buf.Buffer) {
    24  	if destination.Network != net.Network_UDP {
    25  		return
    26  	}
    27  	p.conn.WriteTo(payload.Bytes(), &net.UDPAddr{IP: destination.Address.IP(), Port: int(destination.Port.Value())})
    28  }
    29  
    30  func (p PacketAddrDispatcher) readWorker() {
    31  	for {
    32  		readBuf := buf.New()
    33  		n, addr, err := p.conn.ReadFrom(readBuf.Extend(2048))
    34  		if err != nil {
    35  			return
    36  		}
    37  		readBuf.Resize(0, int32(n))
    38  		p.callback(p.ctx, &udp.Packet{Payload: readBuf, Source: net.DestinationFromAddr(addr)})
    39  	}
    40  }
    41  
    42  type PacketAddrDispatcherCreator struct {
    43  	ctx context.Context
    44  }
    45  
    46  func NewPacketAddrDispatcherCreator(ctx context.Context) PacketAddrDispatcherCreator {
    47  	return PacketAddrDispatcherCreator{ctx: ctx}
    48  }
    49  
    50  func (pdc *PacketAddrDispatcherCreator) NewPacketAddrDispatcher(
    51  	dispatcher routing.Dispatcher, callback ResponseCallback,
    52  ) DispatcherI {
    53  	packetConn, _ := packetaddr.CreatePacketAddrConn(pdc.ctx, dispatcher, false)
    54  	pd := &PacketAddrDispatcher{conn: packetConn, callback: callback, ctx: pdc.ctx}
    55  	go pd.readWorker()
    56  	return pd
    57  }