freedom.go 1.9 KB

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