freedom.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. ray.OutboundOutput().Close()
  57. }()
  58. writeMutex.Lock()
  59. if tcpConn, ok := conn.(*net.TCPConn); ok {
  60. tcpConn.CloseWrite()
  61. }
  62. readMutex.Lock()
  63. return nil
  64. }