1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-25 00:45:24 +00:00
v2fly/proxy/freedom/freedom.go

74 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 (
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
"github.com/v2ray/v2ray-core"
2015-09-19 22:50:21 +00:00
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
2015-09-09 15:39:06 +00:00
)
2015-09-12 20:11:54 +00:00
type FreedomConnection struct {
packet v2net.Packet
2015-09-09 15:39:06 +00:00
}
func NewFreedomConnection(firstPacket v2net.Packet) *FreedomConnection {
2015-09-16 14:27:36 +00:00
return &FreedomConnection{
packet: firstPacket,
2015-09-16 14:27:36 +00:00
}
2015-09-09 15:39:06 +00:00
}
2015-09-12 20:11:54 +00:00
func (vconn *FreedomConnection) Start(ray core.OutboundRay) error {
conn, err := net.Dial(vconn.packet.Destination().Network(), vconn.packet.Destination().Address().String())
log.Info("Freedom: Opening connection to %s", vconn.packet.Destination().String())
2015-09-09 15:39:25 +00:00
if err != nil {
if ray != nil {
close(ray.OutboundOutput())
}
return log.Error("Freedom: Failed to open connection: %s : %v", vconn.packet.Destination().String(), err)
}
if chunk := vconn.packet.Chunk(); chunk != nil {
conn.Write(chunk)
2015-09-09 15:39:25 +00:00
}
if !vconn.packet.MoreChunks() {
if ray != nil {
close(ray.OutboundOutput())
}
return nil
}
input := ray.OutboundInput()
output := ray.OutboundOutput()
2015-09-23 12:14:53 +00:00
var readMutex, writeMutex sync.Mutex
readMutex.Lock()
writeMutex.Lock()
2015-09-14 16:19:17 +00:00
2015-09-23 15:13:50 +00:00
go dumpInput(conn, input, &writeMutex)
go dumpOutput(conn, output, &readMutex)
2015-09-22 16:31:06 +00:00
2015-09-22 16:43:30 +00:00
go func() {
2015-09-23 12:14:53 +00:00
writeMutex.Lock()
2015-09-22 16:43:30 +00:00
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.CloseWrite()
}
2015-09-23 12:14:53 +00:00
readMutex.Lock()
2015-09-22 16:43:30 +00:00
conn.Close()
}()
2015-09-09 22:50:21 +00:00
return nil
2015-09-09 15:39:06 +00:00
}
2015-09-23 15:13:50 +00:00
func dumpInput(conn net.Conn, input <-chan []byte, finish *sync.Mutex) {
2015-09-13 18:01:50 +00:00
v2net.ChanToWriter(conn, input)
2015-09-23 12:14:53 +00:00
finish.Unlock()
2015-09-09 15:39:06 +00:00
}
2015-09-23 15:13:50 +00:00
func dumpOutput(conn net.Conn, output chan<- []byte, finish *sync.Mutex) {
2015-09-13 18:01:50 +00:00
v2net.ReaderToChan(output, conn)
2015-09-23 12:14:53 +00:00
finish.Unlock()
2015-09-13 18:01:50 +00:00
close(output)
2015-09-09 15:39:06 +00:00
}