1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-10 14:26:26 -05:00
v2fly/transport/internet/udp/dispatcher_packetaddr.go

58 lines
1.5 KiB
Go
Raw Normal View History

2021-12-13 16:52:57 -05:00
package udp
import (
"context"
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/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/features/routing"
2021-12-13 16:52:57 -05:00
)
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())})
}
2021-12-31 16:22:16 -05:00
2021-12-13 16:52:57 -05:00
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(
2022-04-06 12:06:08 -04:00
dispatcher routing.Dispatcher, callback ResponseCallback,
) DispatcherI {
2021-12-24 16:42:26 -05:00
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
}