You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.0 KiB

4 years ago
package tunnel
import (
"io"
"net"
"sync"
"time"
"github.com/xjasonlyu/tun2socks/v2/common/pool"
M "github.com/xjasonlyu/tun2socks/v2/constant"
"github.com/xjasonlyu/tun2socks/v2/core"
"github.com/xjasonlyu/tun2socks/v2/log"
"github.com/xjasonlyu/tun2socks/v2/proxy"
"github.com/xjasonlyu/tun2socks/v2/tunnel/statistic"
4 years ago
)
const (
4 years ago
tcpWaitTimeout = 5 * time.Second
4 years ago
)
func newTCPTracker(conn net.Conn, metadata *M.Metadata) net.Conn {
return statistic.NewTCPTracker(conn, metadata, statistic.DefaultManager)
}
func handleTCP(localConn core.TCPConn) {
4 years ago
defer localConn.Close()
id := localConn.ID()
metadata := &M.Metadata{
Net: M.TCP,
SrcIP: net.IP(id.RemoteAddress),
SrcPort: id.RemotePort,
DstIP: net.IP(id.LocalAddress),
DstPort: id.LocalPort,
}
4 years ago
targetConn, err := proxy.Dial(metadata)
if err != nil {
log.Warnf("[TCP] dial %s error: %v", metadata.DestinationAddress(), err)
return
}
if dialerAddr, ok := targetConn.LocalAddr().(*net.TCPAddr); ok {
metadata.MidIP = dialerAddr.IP
metadata.MidPort = uint16(dialerAddr.Port)
4 years ago
} else { /* fallback */
metadata.MidIP, metadata.MidPort = parseAddr(targetConn.LocalAddr().String())
4 years ago
}
4 years ago
targetConn = newTCPTracker(targetConn, metadata)
4 years ago
defer targetConn.Close()
4 years ago
log.Infof("[TCP] %s <-> %s", metadata.SourceAddress(), metadata.DestinationAddress())
4 years ago
relay(localConn, targetConn) /* relay connections */
}
// relay copies between left and right bidirectionally.
func relay(left, right net.Conn) {
4 years ago
wg := sync.WaitGroup{}
4 years ago
wg.Add(2)
go func() {
defer wg.Done()
_ = copyBuffer(right, left) /* ignore error */
right.SetReadDeadline(time.Now().Add(tcpWaitTimeout))
}()
go func() {
defer wg.Done()
_ = copyBuffer(left, right) /* ignore error */
left.SetReadDeadline(time.Now().Add(tcpWaitTimeout))
}()
wg.Wait()
}
func copyBuffer(dst io.Writer, src io.Reader) error {
4 years ago
buf := pool.Get(pool.RelayBufferSize)
4 years ago
defer pool.Put(buf)
_, err := io.CopyBuffer(dst, src, buf)
return err
}