mirror of
https://github.com/xjasonlyu/tun2socks.git
synced 2025-10-21 15:59:22 +08:00
update
This commit is contained in:
88
proxy/tcp.go
Normal file
88
proxy/tcp.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/proxy"
|
||||
|
||||
"github.com/xjasonlyu/tun2socks/common/dns"
|
||||
"github.com/xjasonlyu/tun2socks/common/log"
|
||||
"github.com/xjasonlyu/tun2socks/common/lsof"
|
||||
"github.com/xjasonlyu/tun2socks/common/stats"
|
||||
"github.com/xjasonlyu/tun2socks/core"
|
||||
)
|
||||
|
||||
type tcpHandler struct {
|
||||
proxyHost string
|
||||
proxyPort uint16
|
||||
|
||||
fakeDns dns.FakeDns
|
||||
sessionStater stats.SessionStater
|
||||
}
|
||||
|
||||
func NewTCPHandler(proxyHost string, proxyPort uint16, fakeDns dns.FakeDns, sessionStater stats.SessionStater) core.TCPConnHandler {
|
||||
return &tcpHandler{
|
||||
proxyHost: proxyHost,
|
||||
proxyPort: proxyPort,
|
||||
fakeDns: fakeDns,
|
||||
sessionStater: sessionStater,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *tcpHandler) Handle(localConn net.Conn, target *net.TCPAddr) error {
|
||||
dialer, err := proxy.SOCKS5("tcp", core.ParseTCPAddr(h.proxyHost, h.proxyPort).String(), nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Replace with a domain name if target address IP is a fake IP.
|
||||
var targetHost = target.IP.String()
|
||||
if h.fakeDns != nil {
|
||||
if host, exist := h.fakeDns.IPToHost(target.IP); exist {
|
||||
targetHost = host
|
||||
}
|
||||
}
|
||||
|
||||
targetAddr := net.JoinHostPort(targetHost, strconv.Itoa(target.Port))
|
||||
remoteConn, err := dialer.Dial("tcp", targetAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get name of the process.
|
||||
var process = lsof.GetProcessName(localConn.LocalAddr())
|
||||
if h.sessionStater != nil {
|
||||
sess := &stats.Session{
|
||||
ProcessName: process,
|
||||
Network: localConn.LocalAddr().Network(),
|
||||
DialerAddr: remoteConn.LocalAddr().String(),
|
||||
ClientAddr: localConn.LocalAddr().String(),
|
||||
TargetAddr: targetAddr,
|
||||
UploadBytes: 0,
|
||||
DownloadBytes: 0,
|
||||
SessionStart: time.Now(),
|
||||
}
|
||||
h.sessionStater.AddSession(localConn, sess)
|
||||
|
||||
remoteConn = stats.NewSessionConn(remoteConn, sess)
|
||||
}
|
||||
|
||||
// set keepalive
|
||||
tcpKeepAlive(localConn)
|
||||
tcpKeepAlive(remoteConn)
|
||||
|
||||
go func() {
|
||||
// relay connections
|
||||
tcpRelay(localConn, remoteConn)
|
||||
|
||||
// remove session
|
||||
if h.sessionStater != nil {
|
||||
h.sessionStater.RemoveSession(localConn)
|
||||
}
|
||||
}()
|
||||
|
||||
log.Access(process, "proxy", target.Network(), localConn.LocalAddr().String(), targetAddr)
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user