freedom.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package freedom
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. v2io "github.com/v2ray/v2ray-core/common/io"
  7. "github.com/v2ray/v2ray-core/common/log"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. "github.com/v2ray/v2ray-core/common/retry"
  10. "github.com/v2ray/v2ray-core/transport/dialer"
  11. "github.com/v2ray/v2ray-core/transport/ray"
  12. )
  13. type FreedomConnection struct {
  14. }
  15. func (this *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
  16. log.Info("Freedom: Opening connection to ", firstPacket.Destination())
  17. var conn net.Conn
  18. err := retry.Timed(5, 100).On(func() error {
  19. rawConn, err := dialer.Dial(firstPacket.Destination())
  20. if err != nil {
  21. return err
  22. }
  23. conn = rawConn
  24. return nil
  25. })
  26. if err != nil {
  27. close(ray.OutboundOutput())
  28. log.Error("Freedom: Failed to open connection to ", firstPacket.Destination(), ": ", err)
  29. return err
  30. }
  31. defer conn.Close()
  32. input := ray.OutboundInput()
  33. output := ray.OutboundOutput()
  34. var readMutex, writeMutex sync.Mutex
  35. readMutex.Lock()
  36. writeMutex.Lock()
  37. if chunk := firstPacket.Chunk(); chunk != nil {
  38. conn.Write(chunk.Value)
  39. chunk.Release()
  40. }
  41. if !firstPacket.MoreChunks() {
  42. writeMutex.Unlock()
  43. } else {
  44. go func() {
  45. v2io.ChanToRawWriter(conn, input)
  46. writeMutex.Unlock()
  47. }()
  48. }
  49. go func() {
  50. defer readMutex.Unlock()
  51. defer close(output)
  52. var reader io.Reader
  53. reader = conn
  54. if firstPacket.Destination().IsUDP() {
  55. reader = v2net.NewTimeOutReader(16 /* seconds */, conn)
  56. }
  57. v2io.RawReaderToChan(output, reader)
  58. }()
  59. writeMutex.Lock()
  60. if tcpConn, ok := conn.(*net.TCPConn); ok {
  61. tcpConn.CloseWrite()
  62. }
  63. readMutex.Lock()
  64. return nil
  65. }