mirror of
https://github.com/xjasonlyu/tun2socks.git
synced 2025-10-29 03:02:30 +08:00
Refactor(tunnel): modularize tunnel pkg (#393)
This commit is contained in:
@@ -10,19 +10,11 @@ import (
|
||||
"github.com/xjasonlyu/tun2socks/v2/core/adapter"
|
||||
"github.com/xjasonlyu/tun2socks/v2/log"
|
||||
M "github.com/xjasonlyu/tun2socks/v2/metadata"
|
||||
"github.com/xjasonlyu/tun2socks/v2/proxy"
|
||||
"github.com/xjasonlyu/tun2socks/v2/tunnel/statistic"
|
||||
)
|
||||
|
||||
// _udpSessionTimeout is the default timeout for each UDP session.
|
||||
var _udpSessionTimeout = 60 * time.Second
|
||||
|
||||
func SetUDPTimeout(t time.Duration) {
|
||||
_udpSessionTimeout = t
|
||||
}
|
||||
|
||||
// TODO: Port Restricted NAT support.
|
||||
func handleUDPConn(uc adapter.UDPConn) {
|
||||
func (t *Tunnel) handleUDPConn(uc adapter.UDPConn) {
|
||||
defer uc.Close()
|
||||
|
||||
id := uc.ID()
|
||||
@@ -34,14 +26,14 @@ func handleUDPConn(uc adapter.UDPConn) {
|
||||
DstPort: id.LocalPort,
|
||||
}
|
||||
|
||||
pc, err := proxy.DialUDP(metadata)
|
||||
pc, err := t.Dialer().DialUDP(metadata)
|
||||
if err != nil {
|
||||
log.Warnf("[UDP] dial %s: %v", metadata.DestinationAddress(), err)
|
||||
return
|
||||
}
|
||||
metadata.MidIP, metadata.MidPort = parseAddr(pc.LocalAddr())
|
||||
|
||||
pc = statistic.DefaultUDPTracker(pc, metadata)
|
||||
pc = statistic.NewUDPTracker(pc, metadata, t.manager)
|
||||
defer pc.Close()
|
||||
|
||||
var remote net.Addr
|
||||
@@ -53,22 +45,22 @@ func handleUDPConn(uc adapter.UDPConn) {
|
||||
pc = newSymmetricNATPacketConn(pc, metadata)
|
||||
|
||||
log.Infof("[UDP] %s <-> %s", metadata.SourceAddress(), metadata.DestinationAddress())
|
||||
pipePacket(uc, pc, remote)
|
||||
pipePacket(uc, pc, remote, t.udpTimeout.Load())
|
||||
}
|
||||
|
||||
func pipePacket(origin, remote net.PacketConn, to net.Addr) {
|
||||
func pipePacket(origin, remote net.PacketConn, to net.Addr, timeout time.Duration) {
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(2)
|
||||
|
||||
go unidirectionalPacketStream(remote, origin, to, "origin->remote", &wg)
|
||||
go unidirectionalPacketStream(origin, remote, nil, "remote->origin", &wg)
|
||||
go unidirectionalPacketStream(remote, origin, to, "origin->remote", &wg, timeout)
|
||||
go unidirectionalPacketStream(origin, remote, nil, "remote->origin", &wg, timeout)
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func unidirectionalPacketStream(dst, src net.PacketConn, to net.Addr, dir string, wg *sync.WaitGroup) {
|
||||
func unidirectionalPacketStream(dst, src net.PacketConn, to net.Addr, dir string, wg *sync.WaitGroup, timeout time.Duration) {
|
||||
defer wg.Done()
|
||||
if err := copyPacketData(dst, src, to, _udpSessionTimeout); err != nil {
|
||||
if err := copyPacketData(dst, src, to, timeout); err != nil {
|
||||
log.Debugf("[UDP] copy data for %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user