freedom.go 1.6 KB

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