1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-16 00:48:14 -04:00
v2fly/transport/hub/udp_server.go

74 lines
1.9 KiB
Go
Raw Normal View History

2016-02-01 10:36:33 -05:00
package hub
import (
"sync"
"github.com/v2ray/v2ray-core/app/dispatcher"
2016-04-25 18:13:26 -04:00
"github.com/v2ray/v2ray-core/common/alloc"
2016-02-01 10:36:33 -05:00
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/transport/ray"
)
2016-04-25 18:13:26 -04:00
type UDPResponseCallback func(destination v2net.Destination, payload *alloc.Buffer)
2016-02-01 10:36:33 -05:00
type connEntry struct {
inboundRay ray.InboundRay
callback UDPResponseCallback
}
type UDPServer struct {
sync.RWMutex
conns map[string]*connEntry
packetDispatcher dispatcher.PacketDispatcher
}
func NewUDPServer(packetDispatcher dispatcher.PacketDispatcher) *UDPServer {
return &UDPServer{
conns: make(map[string]*connEntry),
packetDispatcher: packetDispatcher,
}
}
2016-04-25 18:13:26 -04:00
func (this *UDPServer) locateExistingAndDispatch(dest string, payload *alloc.Buffer) bool {
2016-02-01 10:36:33 -05:00
this.RLock()
defer this.RUnlock()
if entry, found := this.conns[dest]; found {
2016-04-25 18:13:26 -04:00
entry.inboundRay.InboundInput().Write(payload)
2016-02-01 10:36:33 -05:00
return true
}
return false
}
2016-04-25 18:13:26 -04:00
func (this *UDPServer) Dispatch(source v2net.Destination, destination v2net.Destination, payload *alloc.Buffer, callback UDPResponseCallback) {
destString := source.String() + "-" + destination.NetAddr()
if this.locateExistingAndDispatch(destString, payload) {
2016-02-01 10:36:33 -05:00
return
}
this.Lock()
2016-04-25 18:13:26 -04:00
inboundRay := this.packetDispatcher.DispatchToOutbound(destination)
inboundRay.InboundInput().Write(payload)
2016-02-01 10:36:33 -05:00
this.conns[destString] = &connEntry{
inboundRay: inboundRay,
callback: callback,
}
this.Unlock()
go this.handleConnection(destString, inboundRay, source, callback)
}
func (this *UDPServer) handleConnection(destString string, inboundRay ray.InboundRay, source v2net.Destination, callback UDPResponseCallback) {
2016-04-18 12:44:10 -04:00
for {
data, err := inboundRay.InboundOutput().Read()
if err != nil {
break
}
2016-04-25 18:13:26 -04:00
callback(source, data)
2016-02-01 10:36:33 -05:00
}
this.Lock()
2016-05-02 08:03:58 -04:00
inboundRay.InboundInput().Release()
inboundRay.InboundOutput().Release()
2016-02-01 10:36:33 -05:00
delete(this.conns, destString)
this.Unlock()
}