1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-26 13:56:12 -04:00
v2fly/proxy/freedom/freedom.go

89 lines
2.0 KiB
Go
Raw Normal View History

2015-09-11 08:12:09 -04:00
package freedom
2015-09-09 11:39:06 -04:00
import (
2015-09-09 11:39:25 -04:00
"net"
2015-09-23 08:14:53 -04:00
"sync"
2015-09-09 18:50:21 -04:00
2015-12-06 05:00:10 -05:00
"github.com/v2ray/v2ray-core/app"
2015-09-19 18:50:21 -04:00
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
2015-10-14 08:51:19 -04:00
"github.com/v2ray/v2ray-core/transport/ray"
2015-09-09 11:39:06 -04:00
)
2015-09-12 16:11:54 -04:00
type FreedomConnection struct {
space app.Space
2015-09-09 11:39:06 -04:00
}
2015-11-27 15:50:28 -05:00
func (this *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
2015-10-06 18:30:44 -04:00
conn, err := net.Dial(firstPacket.Destination().Network(), firstPacket.Destination().Address().String())
log.Info("Freedom: Opening connection to %s", firstPacket.Destination().String())
2015-09-09 11:39:25 -04:00
if err != nil {
2015-10-10 14:52:31 -04:00
close(ray.OutboundOutput())
log.Error("Freedom: Failed to open connection: %s : %v", firstPacket.Destination().String(), err)
return err
}
2015-10-02 09:32:26 -04:00
input := ray.OutboundInput()
output := ray.OutboundOutput()
var readMutex, writeMutex sync.Mutex
readMutex.Lock()
writeMutex.Lock()
2015-10-06 18:30:44 -04:00
if chunk := firstPacket.Chunk(); chunk != nil {
conn.Write(chunk.Value)
chunk.Release()
2015-09-09 11:39:25 -04:00
}
2015-10-06 18:30:44 -04:00
if !firstPacket.MoreChunks() {
2015-10-02 09:32:26 -04:00
writeMutex.Unlock()
} else {
2015-11-27 15:50:28 -05:00
go func() {
v2net.ChanToWriter(conn, input)
writeMutex.Unlock()
}()
}
2015-11-27 15:50:28 -05:00
go func() {
defer readMutex.Unlock()
defer close(output)
response, err := v2net.ReadFrom(conn, nil)
log.Info("Freedom receives %d bytes from %s", response.Len(), conn.RemoteAddr().String())
if response.Len() > 0 {
output <- response
} else {
response.Release()
}
if err != nil {
return
}
if firstPacket.Destination().IsUDP() {
return
}
v2net.ReaderToChan(output, conn)
}()
2015-09-22 12:31:06 -04:00
2015-12-06 05:00:10 -05:00
if this.space.HasDnsCache() {
if firstPacket.Destination().Address().IsDomain() {
domain := firstPacket.Destination().Address().Domain()
addr := conn.RemoteAddr()
switch typedAddr := addr.(type) {
case *net.TCPAddr:
this.space.DnsCache().Add(domain, typedAddr.IP)
case *net.UDPAddr:
this.space.DnsCache().Add(domain, typedAddr.IP)
}
}
}
2015-10-09 19:25:12 -04:00
writeMutex.Lock()
2015-12-15 10:00:47 -05:00
//if tcpConn, ok := conn.(*net.TCPConn); ok {
// tcpConn.CloseWrite()
//}
2015-10-09 19:25:12 -04:00
readMutex.Lock()
conn.Close()
2015-09-22 12:43:30 -04:00
2015-09-09 18:50:21 -04:00
return nil
2015-09-09 11:39:06 -04:00
}