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().NetAddr())
  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. defer conn.Close()
  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. if this.space.HasDnsCache() {
  58. if firstPacket.Destination().Address().IsDomain() {
  59. domain := firstPacket.Destination().Address().Domain()
  60. addr := conn.RemoteAddr()
  61. switch typedAddr := addr.(type) {
  62. case *net.TCPAddr:
  63. this.space.DnsCache().Add(domain, typedAddr.IP)
  64. case *net.UDPAddr:
  65. this.space.DnsCache().Add(domain, typedAddr.IP)
  66. }
  67. }
  68. }
  69. writeMutex.Lock()
  70. if tcpConn, ok := conn.(*net.TCPConn); ok {
  71. tcpConn.CloseWrite()
  72. }
  73. readMutex.Lock()
  74. return nil
  75. }