v2ray-core/net/freedom/freedom.go

71 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
"io"
"net"
2015-09-09 22:50:21 +00:00
"github.com/v2ray/v2ray-core"
2015-09-12 18:36:21 +00:00
"github.com/v2ray/v2ray-core/log"
2015-09-10 22:24:18 +00:00
v2net "github.com/v2ray/v2ray-core/net"
2015-09-09 15:39:06 +00:00
)
2015-09-12 20:11:54 +00:00
type FreedomConnection struct {
dest v2net.Address
2015-09-09 15:39:06 +00:00
}
2015-09-12 20:11:54 +00:00
func NewFreedomConnection(dest v2net.Address) *FreedomConnection {
conn := new(FreedomConnection)
2015-09-10 22:24:18 +00:00
conn.dest = dest
2015-09-09 15:39:25 +00:00
return conn
2015-09-09 15:39:06 +00:00
}
2015-09-12 20:11:54 +00:00
func (vconn *FreedomConnection) Start(ray core.OutboundRay) error {
input := ray.OutboundInput()
output := ray.OutboundOutput()
2015-09-10 22:24:18 +00:00
conn, err := net.Dial("tcp", vconn.dest.String())
2015-09-09 15:39:25 +00:00
if err != nil {
2015-09-12 18:36:21 +00:00
return log.Error("Failed to open tcp: %s", vconn.dest.String())
2015-09-09 15:39:25 +00:00
}
2015-09-12 18:36:21 +00:00
log.Debug("Sending outbound tcp: %s", vconn.dest.String())
2015-09-09 15:39:25 +00:00
finish := make(chan bool, 2)
go vconn.DumpInput(conn, input, finish)
go vconn.DumpOutput(conn, output, finish)
go vconn.CloseConn(conn, finish)
2015-09-09 22:50:21 +00:00
return nil
2015-09-09 15:39:06 +00:00
}
2015-09-12 20:11:54 +00:00
func (vconn *FreedomConnection) DumpInput(conn net.Conn, input <-chan []byte, finish chan<- bool) {
2015-09-09 15:39:25 +00:00
for {
data, open := <-input
if !open {
finish <- true
2015-09-12 18:36:21 +00:00
log.Debug("Freedom finishing input.")
2015-09-09 15:39:25 +00:00
break
}
2015-09-12 18:36:21 +00:00
nBytes, err := conn.Write(data)
log.Debug("Freedom wrote %d bytes with error %v", nBytes, err)
2015-09-09 15:39:25 +00:00
}
2015-09-09 15:39:06 +00:00
}
2015-09-12 20:11:54 +00:00
func (vconn *FreedomConnection) DumpOutput(conn net.Conn, output chan<- []byte, finish chan<- bool) {
2015-09-09 15:39:25 +00:00
for {
2015-09-12 18:36:21 +00:00
buffer := make([]byte, 512)
2015-09-09 15:39:25 +00:00
nBytes, err := conn.Read(buffer)
2015-09-12 18:36:21 +00:00
log.Debug("Freedom reading %d bytes with error %v", nBytes, err)
2015-09-09 15:39:25 +00:00
if err == io.EOF {
2015-09-11 12:12:26 +00:00
close(output)
2015-09-09 15:39:25 +00:00
finish <- true
2015-09-12 18:36:21 +00:00
log.Debug("Freedom finishing output.")
2015-09-09 15:39:25 +00:00
break
}
output <- buffer[:nBytes]
}
2015-09-09 15:39:06 +00:00
}
2015-09-12 20:11:54 +00:00
func (vconn *FreedomConnection) CloseConn(conn net.Conn, finish <-chan bool) {
2015-09-12 22:25:50 +00:00
<-finish
<-finish
2015-09-09 15:39:25 +00:00
conn.Close()
2015-09-09 15:39:06 +00:00
}