freedom.go 1.7 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. defer ray.OutboundOutput().Close()
  21. var conn net.Conn
  22. err := retry.Timed(5, 100).On(func() error {
  23. rawConn, err := dialer.Dial(destination)
  24. if err != nil {
  25. return err
  26. }
  27. conn = rawConn
  28. return nil
  29. })
  30. if err != nil {
  31. log.Error("Freedom: Failed to open connection to ", destination, ": ", err)
  32. return err
  33. }
  34. defer conn.Close()
  35. input := ray.OutboundInput()
  36. output := ray.OutboundOutput()
  37. var readMutex, writeMutex sync.Mutex
  38. readMutex.Lock()
  39. writeMutex.Lock()
  40. conn.Write(payload.Value)
  41. go func() {
  42. v2writer := v2io.NewAdaptiveWriter(conn)
  43. defer v2writer.Release()
  44. v2io.Pipe(input, v2writer)
  45. writeMutex.Unlock()
  46. }()
  47. go func() {
  48. defer readMutex.Unlock()
  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. }