freedom.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. }
  33. if !firstPacket.MoreChunks() {
  34. writeMutex.Unlock()
  35. } else {
  36. go dumpInput(conn, input, &writeMutex)
  37. }
  38. go dumpOutput(conn, output, &readMutex, firstPacket.Destination().IsUDP())
  39. go func() {
  40. writeMutex.Lock()
  41. if tcpConn, ok := conn.(*net.TCPConn); ok {
  42. tcpConn.CloseWrite()
  43. }
  44. readMutex.Lock()
  45. conn.Close()
  46. }()
  47. return nil
  48. }
  49. func dumpInput(conn net.Conn, input <-chan *alloc.Buffer, finish *sync.Mutex) {
  50. v2net.ChanToWriter(conn, input)
  51. finish.Unlock()
  52. }
  53. func dumpOutput(conn net.Conn, output chan<- *alloc.Buffer, finish *sync.Mutex, udp bool) {
  54. defer finish.Unlock()
  55. defer close(output)
  56. response, err := v2net.ReadFrom(conn, nil)
  57. log.Info("Freedom receives %d bytes from %s", response.Len(), conn.RemoteAddr().String())
  58. if response.Len() > 0 {
  59. output <- response
  60. } else {
  61. response.Release()
  62. }
  63. if err != nil {
  64. return
  65. }
  66. if udp {
  67. return
  68. }
  69. v2net.ReaderToChan(output, conn)
  70. }