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-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"
|
2015-09-19 21:54:36 +00:00
|
|
|
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-20 16:22:29 +00:00
|
|
|
dest v2net.Destination
|
2015-09-09 15:39:06 +00:00
|
|
|
}
|
|
|
|
|
2015-09-20 16:22:29 +00:00
|
|
|
func NewFreedomConnection(dest v2net.Destination) *FreedomConnection {
|
2015-09-16 14:27:36 +00:00
|
|
|
return &FreedomConnection{
|
|
|
|
dest: dest,
|
|
|
|
}
|
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-20 14:03:12 +00:00
|
|
|
conn, err := net.Dial(vconn.dest.Network(), vconn.dest.Address().String())
|
|
|
|
log.Info("Freedom: Opening connection to %s", vconn.dest.String())
|
2015-09-09 15:39:25 +00:00
|
|
|
if err != nil {
|
2015-09-17 21:00:17 +00:00
|
|
|
close(output)
|
2015-09-20 14:03:12 +00:00
|
|
|
return log.Error("Freedom: Failed to open connection: %s : %v", vconn.dest.String(), err)
|
2015-09-09 15:39:25 +00:00
|
|
|
}
|
|
|
|
|
2015-09-14 11:51:30 +00:00
|
|
|
readFinish := make(chan bool)
|
2015-09-14 16:19:17 +00:00
|
|
|
writeFinish := make(chan bool)
|
|
|
|
|
2015-09-20 19:21:55 +00:00
|
|
|
go dumpInput(conn, input, writeFinish)
|
|
|
|
go dumpOutput(conn, output, readFinish)
|
|
|
|
go closeConn(conn, readFinish, writeFinish)
|
2015-09-09 22:50:21 +00:00
|
|
|
return nil
|
2015-09-09 15:39:06 +00:00
|
|
|
}
|
|
|
|
|
2015-09-20 19:21:55 +00:00
|
|
|
func dumpInput(conn net.Conn, input <-chan []byte, finish chan<- bool) {
|
2015-09-13 18:01:50 +00:00
|
|
|
v2net.ChanToWriter(conn, input)
|
2015-09-20 19:21:55 +00:00
|
|
|
close(finish)
|
2015-09-09 15:39:06 +00:00
|
|
|
}
|
|
|
|
|
2015-09-20 19:21:55 +00:00
|
|
|
func dumpOutput(conn net.Conn, output chan<- []byte, finish chan<- bool) {
|
2015-09-13 18:01:50 +00:00
|
|
|
v2net.ReaderToChan(output, conn)
|
|
|
|
close(output)
|
2015-09-20 19:21:55 +00:00
|
|
|
close(finish)
|
2015-09-09 15:39:06 +00:00
|
|
|
}
|
|
|
|
|
2015-09-20 19:21:55 +00:00
|
|
|
func closeConn(conn net.Conn, readFinish <-chan bool, writeFinish <-chan bool) {
|
2015-09-14 11:51:30 +00:00
|
|
|
<-writeFinish
|
2015-09-14 16:19:17 +00:00
|
|
|
if tcpConn, ok := conn.(*net.TCPConn); ok {
|
|
|
|
tcpConn.CloseWrite()
|
|
|
|
}
|
2015-09-14 11:51:30 +00:00
|
|
|
<-readFinish
|
2015-09-09 15:39:25 +00:00
|
|
|
conn.Close()
|
2015-09-09 15:39:06 +00:00
|
|
|
}
|