1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/transport/internet/udp/dispatcher_packetaddr.go

55 lines
1.5 KiB
Go
Raw Normal View History

2021-12-13 16:52:57 -05:00
package udp
import (
"context"
"github.com/v2fly/v2ray-core/v4/common/buf"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v4/common/protocol/udp"
"github.com/v2fly/v2ray-core/v4/features/routing"
)
type PacketAddrDispatcher struct {
conn net.PacketConn
callback ResponseCallback
ctx context.Context
}
func (p PacketAddrDispatcher) Close() error {
return p.conn.Close()
}
func (p PacketAddrDispatcher) Dispatch(ctx context.Context, destination net.Destination, payload *buf.Buffer) {
if destination.Network != net.Network_UDP {
return
}
p.conn.WriteTo(payload.Bytes(), &net.UDPAddr{IP: destination.Address.IP(), Port: int(destination.Port.Value())})
}
func (p PacketAddrDispatcher) readWorker() {
for {
readBuf := buf.New()
n, addr, err := p.conn.ReadFrom(readBuf.Extend(2048))
if err != nil {
return
}
readBuf.Resize(0, int32(n))
p.callback(p.ctx, &udp.Packet{Payload: readBuf, Source: net.DestinationFromAddr(addr)})
}
}
type PacketAddrDispatcherCreator struct {
ctx context.Context
}
func NewPacketAddrDispatcherCreator(ctx context.Context) PacketAddrDispatcherCreator {
return PacketAddrDispatcherCreator{ctx: ctx}
}
func (pdc *PacketAddrDispatcherCreator) NewPacketAddrDispatcher(
2021-12-24 16:42:26 -05:00
dispatcher routing.Dispatcher, callback ResponseCallback) DispatcherI {
packetConn, _ := packetaddr.CreatePacketAddrConn(pdc.ctx, dispatcher, false)
2021-12-13 16:52:57 -05:00
pd := &PacketAddrDispatcher{conn: packetConn, callback: callback, ctx: pdc.ctx}
go pd.readWorker()
2021-12-24 16:42:26 -05:00
return pd
2021-12-13 16:52:57 -05:00
}