freedom.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package freedom
  2. import (
  3. "net"
  4. "sync"
  5. "github.com/v2ray/v2ray-core/app"
  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. space app.Space
  12. }
  13. func (this *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
  14. conn, err := net.Dial(firstPacket.Destination().Network(), firstPacket.Destination().Address().String())
  15. log.Info("Freedom: Opening connection to %s", firstPacket.Destination().String())
  16. if err != nil {
  17. close(ray.OutboundOutput())
  18. log.Error("Freedom: Failed to open connection: %s : %v", firstPacket.Destination().String(), err)
  19. return err
  20. }
  21. input := ray.OutboundInput()
  22. output := ray.OutboundOutput()
  23. var readMutex, writeMutex sync.Mutex
  24. readMutex.Lock()
  25. writeMutex.Lock()
  26. if chunk := firstPacket.Chunk(); chunk != nil {
  27. conn.Write(chunk.Value)
  28. chunk.Release()
  29. }
  30. if !firstPacket.MoreChunks() {
  31. writeMutex.Unlock()
  32. } else {
  33. go func() {
  34. v2net.ChanToWriter(conn, input)
  35. writeMutex.Unlock()
  36. }()
  37. }
  38. go func() {
  39. defer readMutex.Unlock()
  40. defer close(output)
  41. response, err := v2net.ReadFrom(conn, nil)
  42. log.Info("Freedom receives %d bytes from %s", response.Len(), conn.RemoteAddr().String())
  43. if response.Len() > 0 {
  44. output <- response
  45. } else {
  46. response.Release()
  47. }
  48. if err != nil {
  49. return
  50. }
  51. if firstPacket.Destination().IsUDP() {
  52. return
  53. }
  54. v2net.ReaderToChan(output, conn)
  55. }()
  56. if this.space.HasDnsCache() {
  57. if firstPacket.Destination().Address().IsDomain() {
  58. domain := firstPacket.Destination().Address().Domain()
  59. addr := conn.RemoteAddr()
  60. switch typedAddr := addr.(type) {
  61. case *net.TCPAddr:
  62. this.space.DnsCache().Add(domain, typedAddr.IP)
  63. case *net.UDPAddr:
  64. this.space.DnsCache().Add(domain, typedAddr.IP)
  65. }
  66. }
  67. }
  68. writeMutex.Lock()
  69. if tcpConn, ok := conn.(*net.TCPConn); ok {
  70. tcpConn.CloseWrite()
  71. }
  72. readMutex.Lock()
  73. conn.Close()
  74. return nil
  75. }