server_udp.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package socks
  2. import (
  3. "github.com/v2ray/v2ray-core/common/alloc"
  4. "github.com/v2ray/v2ray-core/common/log"
  5. v2net "github.com/v2ray/v2ray-core/common/net"
  6. "github.com/v2ray/v2ray-core/proxy/socks/protocol"
  7. "github.com/v2ray/v2ray-core/transport/internet/udp"
  8. )
  9. func (this *Server) listenUDP() error {
  10. this.udpServer = udp.NewUDPServer(this.packetDispatcher)
  11. udpHub, err := udp.ListenUDP(this.meta.Address, this.meta.Port, this.handleUDPPayload)
  12. if err != nil {
  13. log.Error("Socks: Failed to listen on udp ", this.meta.Address, ":", this.meta.Port)
  14. return err
  15. }
  16. this.udpMutex.Lock()
  17. this.udpAddress = v2net.UDPDestination(this.config.Address, this.meta.Port)
  18. this.udpHub = udpHub
  19. this.udpMutex.Unlock()
  20. return nil
  21. }
  22. func (this *Server) handleUDPPayload(payload *alloc.Buffer, source v2net.Destination) {
  23. log.Info("Socks: Client UDP connection from ", source)
  24. request, err := protocol.ReadUDPRequest(payload.Value)
  25. payload.Release()
  26. if err != nil {
  27. log.Error("Socks: Failed to parse UDP request: ", err)
  28. return
  29. }
  30. if request.Data.Len() == 0 {
  31. request.Data.Release()
  32. return
  33. }
  34. if request.Fragment != 0 {
  35. log.Warning("Socks: Dropping fragmented UDP packets.")
  36. // TODO handle fragments
  37. request.Data.Release()
  38. return
  39. }
  40. log.Info("Socks: Send packet to ", request.Destination(), " with ", request.Data.Len(), " bytes")
  41. log.Access(source, request.Destination, log.AccessAccepted, "")
  42. this.udpServer.Dispatch(source, request.Destination(), request.Data, func(destination v2net.Destination, payload *alloc.Buffer) {
  43. response := &protocol.Socks5UDPRequest{
  44. Fragment: 0,
  45. Address: request.Destination().Address(),
  46. Port: request.Destination().Port(),
  47. Data: payload,
  48. }
  49. log.Info("Socks: Writing back UDP response with ", payload.Len(), " bytes to ", destination)
  50. udpMessage := alloc.NewSmallBuffer().Clear()
  51. response.Write(udpMessage)
  52. this.udpMutex.RLock()
  53. if !this.accepting {
  54. this.udpMutex.RUnlock()
  55. return
  56. }
  57. nBytes, err := this.udpHub.WriteTo(udpMessage.Value, destination)
  58. this.udpMutex.RUnlock()
  59. udpMessage.Release()
  60. response.Data.Release()
  61. if err != nil {
  62. log.Error("Socks: failed to write UDP message (", nBytes, " bytes) to ", destination, ": ", err)
  63. }
  64. })
  65. }