1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 10:08:15 -05:00
v2fly/proxy/socks/udp.go

73 lines
2.1 KiB
Go
Raw Normal View History

package socks
import (
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy/socks/protocol"
2016-02-01 10:36:33 -05:00
"github.com/v2ray/v2ray-core/transport/hub"
)
2016-02-06 12:01:27 -05:00
func (this *SocksServer) listenUDP(port v2net.Port) error {
2016-02-03 16:43:09 -05:00
this.udpServer = hub.NewUDPServer(this.packetDispatcher)
udpHub, err := hub.ListenUDP(port, this.handleUDPPayload)
if err != nil {
2016-02-03 16:43:09 -05:00
log.Error("Socks: Failed to listen on udp port ", port)
return err
}
2016-01-04 02:40:24 -05:00
this.udpMutex.Lock()
this.udpAddress = v2net.UDPDestination(this.config.Address, port)
2016-02-03 16:43:09 -05:00
this.udpHub = udpHub
2016-01-04 02:40:24 -05:00
this.udpMutex.Unlock()
return nil
}
2016-02-03 16:43:09 -05:00
func (this *SocksServer) handleUDPPayload(payload *alloc.Buffer, source v2net.Destination) {
log.Info("Socks: Client UDP connection from ", source)
request, err := protocol.ReadUDPRequest(payload.Value)
payload.Release()
if err != nil {
log.Error("Socks: Failed to parse UDP request: ", err)
return
}
if request.Data.Len() == 0 {
request.Data.Release()
return
}
if request.Fragment != 0 {
log.Warning("Socks: Dropping fragmented UDP packets.")
// TODO handle fragments
request.Data.Release()
return
}
udpPacket := v2net.NewPacket(request.Destination(), request.Data, false)
log.Info("Socks: Send packet to ", udpPacket.Destination(), " with ", request.Data.Len(), " bytes")
this.udpServer.Dispatch(source, udpPacket, func(packet v2net.Packet) {
response := &protocol.Socks5UDPRequest{
Fragment: 0,
Address: udpPacket.Destination().Address(),
Port: udpPacket.Destination().Port(),
Data: packet.Chunk(),
}
log.Info("Socks: Writing back UDP response with ", response.Data.Len(), " bytes to ", packet.Destination())
udpMessage := alloc.NewSmallBuffer().Clear()
response.Write(udpMessage)
2016-01-03 18:33:25 -05:00
this.udpMutex.RLock()
if !this.accepting {
2016-01-03 18:33:25 -05:00
this.udpMutex.RUnlock()
2016-02-03 16:43:09 -05:00
return
}
2016-02-03 16:43:09 -05:00
nBytes, err := this.udpHub.WriteTo(udpMessage.Value, packet.Destination())
2016-01-03 18:33:25 -05:00
this.udpMutex.RUnlock()
2016-02-03 16:43:09 -05:00
udpMessage.Release()
response.Data.Release()
if err != nil {
2016-02-03 16:43:09 -05:00
log.Error("Socks: failed to write UDP message (", nBytes, " bytes) to ", packet.Destination(), ": ", err)
}
2016-02-03 16:43:09 -05:00
})
2015-09-28 15:32:07 -04:00
}