freedom.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package freedom
  2. import (
  3. "net"
  4. "sync"
  5. "github.com/v2ray/v2ray-core"
  6. "github.com/v2ray/v2ray-core/common/alloc"
  7. "github.com/v2ray/v2ray-core/common/log"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. )
  10. type FreedomConnection struct {
  11. }
  12. func NewFreedomConnection() *FreedomConnection {
  13. return &FreedomConnection{}
  14. }
  15. func (vconn *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray core.OutboundRay) error {
  16. conn, err := net.Dial(firstPacket.Destination().Network(), firstPacket.Destination().Address().String())
  17. log.Info("Freedom: Opening connection to %s", firstPacket.Destination().String())
  18. if err != nil {
  19. if ray != nil {
  20. close(ray.OutboundOutput())
  21. }
  22. return log.Error("Freedom: Failed to open connection: %s : %v", firstPacket.Destination().String(), err)
  23. }
  24. input := ray.OutboundInput()
  25. output := ray.OutboundOutput()
  26. var readMutex, writeMutex sync.Mutex
  27. readMutex.Lock()
  28. writeMutex.Lock()
  29. if chunk := firstPacket.Chunk(); chunk != nil {
  30. conn.Write(chunk.Value)
  31. chunk.Release()
  32. chunk = nil
  33. }
  34. if !firstPacket.MoreChunks() {
  35. writeMutex.Unlock()
  36. } else {
  37. go dumpInput(conn, input, &writeMutex)
  38. }
  39. go dumpOutput(conn, output, &readMutex, firstPacket.Destination().IsUDP())
  40. go func() {
  41. writeMutex.Lock()
  42. if tcpConn, ok := conn.(*net.TCPConn); ok {
  43. tcpConn.CloseWrite()
  44. }
  45. readMutex.Lock()
  46. conn.Close()
  47. }()
  48. return nil
  49. }
  50. func dumpInput(conn net.Conn, input <-chan *alloc.Buffer, finish *sync.Mutex) {
  51. v2net.ChanToWriter(conn, input)
  52. finish.Unlock()
  53. }
  54. func dumpOutput(conn net.Conn, output chan<- *alloc.Buffer, finish *sync.Mutex, udp bool) {
  55. defer finish.Unlock()
  56. defer close(output)
  57. response, err := v2net.ReadFrom(conn, nil)
  58. log.Info("Freedom receives %d bytes from %s", response.Len(), conn.RemoteAddr().String())
  59. if response.Len() > 0 {
  60. output <- response
  61. } else {
  62. response.Release()
  63. response = nil
  64. }
  65. if err != nil {
  66. return
  67. }
  68. if udp {
  69. return
  70. }
  71. v2net.ReaderToChan(output, conn)
  72. }