freedom.go 1.6 KB

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