freedom.go 1.9 KB

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