freedom.go 1.7 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. defer firstPacket.Release()
  18. defer ray.OutboundInput().Release()
  19. var conn net.Conn
  20. err := retry.Timed(5, 100).On(func() error {
  21. rawConn, err := dialer.Dial(firstPacket.Destination())
  22. if err != nil {
  23. return err
  24. }
  25. conn = rawConn
  26. return nil
  27. })
  28. if err != nil {
  29. log.Error("Freedom: Failed to open connection to ", firstPacket.Destination(), ": ", err)
  30. return err
  31. }
  32. defer conn.Close()
  33. input := ray.OutboundInput()
  34. output := ray.OutboundOutput()
  35. var readMutex, writeMutex sync.Mutex
  36. readMutex.Lock()
  37. writeMutex.Lock()
  38. if chunk := firstPacket.Chunk(); chunk != nil {
  39. conn.Write(chunk.Value)
  40. }
  41. if !firstPacket.MoreChunks() {
  42. writeMutex.Unlock()
  43. } else {
  44. go func() {
  45. v2io.Pipe(input, v2io.NewAdaptiveWriter(conn))
  46. writeMutex.Unlock()
  47. }()
  48. }
  49. go func() {
  50. defer readMutex.Unlock()
  51. defer output.Close()
  52. var reader io.Reader = conn
  53. if firstPacket.Destination().IsUDP() {
  54. reader = v2net.NewTimeOutReader(16 /* seconds */, conn)
  55. }
  56. v2io.Pipe(v2io.NewAdaptiveReader(reader), output)
  57. }()
  58. writeMutex.Lock()
  59. if tcpConn, ok := conn.(*net.TCPConn); ok {
  60. tcpConn.CloseWrite()
  61. }
  62. readMutex.Lock()
  63. return nil
  64. }