v2ray-core/transport/internet/udp/udp_server.go

83 lines
1.9 KiB
Go
Raw Normal View History

2016-06-14 20:54:08 +00:00
package udp
2016-02-01 15:36:33 +00:00
import (
"context"
2016-02-01 15:36:33 +00:00
"sync"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/app/dispatcher"
2016-12-09 10:35:27 +00:00
"v2ray.com/core/common/buf"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/log"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/ray"
2016-02-01 15:36:33 +00:00
)
type ResponseCallback func(payload *buf.Buffer)
2016-02-01 15:36:33 +00:00
2016-12-21 14:37:16 +00:00
type Server struct {
2016-02-01 15:36:33 +00:00
sync.RWMutex
conns map[string]ray.InboundRay
2017-01-13 12:53:44 +00:00
packetDispatcher dispatcher.Interface
2016-02-01 15:36:33 +00:00
}
2017-01-13 12:53:44 +00:00
func NewServer(packetDispatcher dispatcher.Interface) *Server {
2016-12-21 14:37:16 +00:00
return &Server{
conns: make(map[string]ray.InboundRay),
2016-02-01 15:36:33 +00:00
packetDispatcher: packetDispatcher,
}
}
2016-12-21 14:37:16 +00:00
func (v *Server) RemoveRay(name string) {
2016-11-27 20:39:09 +00:00
v.Lock()
defer v.Unlock()
if conn, found := v.conns[name]; found {
conn.InboundInput().Close()
conn.InboundOutput().Close()
delete(v.conns, name)
2016-02-01 15:36:33 +00:00
}
}
func (v *Server) getInboundRay(ctx context.Context, dest v2net.Destination) (ray.InboundRay, bool) {
destString := dest.String()
2017-01-06 10:40:59 +00:00
v.Lock()
defer v.Unlock()
if entry, found := v.conns[destString]; found {
2017-01-06 10:40:59 +00:00
return entry, true
}
log.Info("UDP|Server: establishing new connection for ", dest)
ctx = proxy.ContextWithDestination(ctx, dest)
return v.packetDispatcher.DispatchToOutbound(ctx), false
2017-01-06 10:40:59 +00:00
}
func (v *Server) Dispatch(ctx context.Context, destination v2net.Destination, payload *buf.Buffer, callback ResponseCallback) {
2016-08-14 15:08:01 +00:00
// TODO: Add user to destString
destString := destination.String()
2017-01-06 10:40:59 +00:00
log.Debug("UDP|Server: Dispatch request: ", destString)
inboundRay, existing := v.getInboundRay(ctx, destination)
2017-01-06 10:40:59 +00:00
outputStream := inboundRay.InboundInput()
2016-05-13 00:20:07 +00:00
if outputStream != nil {
if err := outputStream.Write(payload); err != nil {
v.RemoveRay(destString)
}
2016-05-13 00:20:07 +00:00
}
2017-01-06 10:40:59 +00:00
if !existing {
go func() {
handleInput(inboundRay.InboundOutput(), callback)
v.RemoveRay(destString)
}()
2017-01-06 10:40:59 +00:00
}
2016-02-01 15:36:33 +00:00
}
func handleInput(input ray.InputStream, callback ResponseCallback) {
2016-04-18 16:44:10 +00:00
for {
data, err := input.Read()
2016-04-18 16:44:10 +00:00
if err != nil {
break
}
callback(data)
2016-02-01 15:36:33 +00:00
}
}