v2ray-core/proxy/freedom/freedom.go

79 lines
1.6 KiB
Go
Raw Normal View History

2015-09-11 12:12:09 +00:00
package freedom
2015-09-09 15:39:06 +00:00
import (
2016-02-01 15:36:33 +00:00
"io"
2015-09-09 15:39:25 +00:00
"net"
2015-09-23 12:14:53 +00:00
"sync"
2015-09-09 22:50:21 +00:00
2016-01-29 13:39:55 +00:00
v2io "github.com/v2ray/v2ray-core/common/io"
2015-09-19 22:50:21 +00:00
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
2015-12-17 00:19:04 +00:00
"github.com/v2ray/v2ray-core/common/retry"
"github.com/v2ray/v2ray-core/transport/dialer"
2015-10-14 12:51:19 +00:00
"github.com/v2ray/v2ray-core/transport/ray"
2015-09-09 15:39:06 +00:00
)
2015-09-12 20:11:54 +00:00
type FreedomConnection struct {
2015-09-09 15:39:06 +00:00
}
2015-11-27 20:50:28 +00:00
func (this *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
2016-01-18 11:24:33 +00:00
log.Info("Freedom: Opening connection to ", firstPacket.Destination())
2015-12-17 00:19:04 +00:00
var conn net.Conn
err := retry.Timed(5, 100).On(func() error {
rawConn, err := dialer.Dial(firstPacket.Destination())
if err != nil {
return err
}
conn = rawConn
return nil
})
2015-09-09 15:39:25 +00:00
if err != nil {
2015-10-10 18:52:31 +00:00
close(ray.OutboundOutput())
2016-01-18 11:24:33 +00:00
log.Error("Freedom: Failed to open connection to ", firstPacket.Destination(), ": ", err)
return err
}
2015-12-15 15:38:25 +00:00
defer conn.Close()
2015-10-02 13:32:26 +00:00
input := ray.OutboundInput()
output := ray.OutboundOutput()
var readMutex, writeMutex sync.Mutex
readMutex.Lock()
writeMutex.Lock()
2015-10-06 22:30:44 +00:00
if chunk := firstPacket.Chunk(); chunk != nil {
conn.Write(chunk.Value)
chunk.Release()
2015-09-09 15:39:25 +00:00
}
2015-10-06 22:30:44 +00:00
if !firstPacket.MoreChunks() {
2015-10-02 13:32:26 +00:00
writeMutex.Unlock()
} else {
2015-11-27 20:50:28 +00:00
go func() {
2016-02-01 11:22:29 +00:00
v2io.ChanToRawWriter(conn, input)
2015-11-27 20:50:28 +00:00
writeMutex.Unlock()
}()
}
2015-11-27 20:50:28 +00:00
go func() {
defer readMutex.Unlock()
defer close(output)
2016-02-03 20:36:52 +00:00
var reader io.Reader = conn
2015-11-27 20:50:28 +00:00
if firstPacket.Destination().IsUDP() {
2016-02-01 14:06:03 +00:00
reader = v2net.NewTimeOutReader(16 /* seconds */, conn)
2015-11-27 20:50:28 +00:00
}
v2io.RawReaderToChan(output, reader)
2015-11-27 20:50:28 +00:00
}()
2015-09-22 16:31:06 +00:00
2015-10-09 23:25:12 +00:00
writeMutex.Lock()
2015-12-15 15:38:25 +00:00
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.CloseWrite()
}
2015-10-09 23:25:12 +00:00
readMutex.Lock()
2015-09-22 16:43:30 +00:00
2015-09-09 22:50:21 +00:00
return nil
2015-09-09 15:39:06 +00:00
}