server_udp.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/hub"
  8. )
  9. func (this *Server) listenUDP(port v2net.Port) error {
  10. this.udpServer = hub.NewUDPServer(this.packetDispatcher)
  11. udpHub, err := hub.ListenUDP(port, this.handleUDPPayload)
  12. if err != nil {
  13. log.Error("Socks: Failed to listen on udp port ", port)
  14. return err
  15. }
  16. this.udpMutex.Lock()
  17. this.udpAddress = v2net.UDPDestination(this.config.Address, 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. this.udpServer.Dispatch(source, request.Destination(), request.Data, func(destination v2net.Destination, payload *alloc.Buffer) {
  42. response := &protocol.Socks5UDPRequest{
  43. Fragment: 0,
  44. Address: request.Destination().Address(),
  45. Port: request.Destination().Port(),
  46. Data: payload,
  47. }
  48. log.Info("Socks: Writing back UDP response with ", payload.Len(), " bytes to ", destination)
  49. udpMessage := alloc.NewSmallBuffer().Clear()
  50. response.Write(udpMessage)
  51. this.udpMutex.RLock()
  52. if !this.accepting {
  53. this.udpMutex.RUnlock()
  54. return
  55. }
  56. nBytes, err := this.udpHub.WriteTo(udpMessage.Value, destination)
  57. this.udpMutex.RUnlock()
  58. udpMessage.Release()
  59. response.Data.Release()
  60. if err != nil {
  61. log.Error("Socks: failed to write UDP message (", nBytes, " bytes) to ", destination, ": ", err)
  62. }
  63. })
  64. }