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

82 lines
1.9 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"
"github.com/v2ray/v2ray-core/common/alloc"
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 {
2015-09-09 15:39:06 +00:00
}
2015-10-06 22:30:44 +00:00
func NewFreedomConnection() *FreedomConnection {
return &FreedomConnection{}
2015-09-09 15:39:06 +00:00
}
2015-10-06 22:30:44 +00:00
func (vconn *FreedomConnection) Dispatch(firstPacket v2net.Packet, ray core.OutboundRay) error {
conn, err := net.Dial(firstPacket.Destination().Network(), firstPacket.Destination().Address().String())
log.Info("Freedom: Opening connection to %s", firstPacket.Destination().String())
2015-09-09 15:39:25 +00:00
if err != nil {
2015-10-10 18:52:31 +00:00
close(ray.OutboundOutput())
2015-10-06 22:30:44 +00:00
return log.Error("Freedom: Failed to open connection: %s : %v", firstPacket.Destination().String(), err)
}
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 {
go dumpInput(conn, input, &writeMutex)
}
2015-10-06 22:30:44 +00:00
go dumpOutput(conn, output, &readMutex, firstPacket.Destination().IsUDP())
2015-09-22 16:31:06 +00:00
2015-10-09 23:25:12 +00:00
writeMutex.Lock()
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.CloseWrite()
}
readMutex.Lock()
conn.Close()
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
}
func dumpInput(conn net.Conn, input <-chan *alloc.Buffer, 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
}
func dumpOutput(conn net.Conn, output chan<- *alloc.Buffer, finish *sync.Mutex, udp bool) {
2015-10-03 22:58:07 +00:00
defer finish.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 {
2015-10-03 22:58:07 +00:00
output <- response
} else {
response.Release()
2015-10-03 22:58:07 +00:00
}
if err != nil {
return
}
if udp {
return
}
2015-09-13 18:01:50 +00:00
v2net.ReaderToChan(output, conn)
2015-09-09 15:39:06 +00:00
}