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.

102 lines
2.5 KiB

4 years ago
package tunnel
import (
"errors"
"net"
"os"
"time"
"github.com/xjasonlyu/tun2socks/v2/common/pool"
"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"
4 years ago
)
// _udpSessionTimeout is the default timeout for each UDP session.
var _udpSessionTimeout = 60 * time.Second
4 years ago
func SetUDPTimeout(t time.Duration) {
_udpSessionTimeout = t
}
func newUDPTracker(conn net.PacketConn, metadata *M.Metadata) net.PacketConn {
return statistic.NewUDPTracker(conn, metadata, statistic.DefaultManager)
}
3 years ago
// TODO: Port Restricted NAT support.
func handleUDPConn(uc adapter.UDPConn) {
defer uc.Close()
id := uc.ID()
metadata := &M.Metadata{
Network: M.UDP,
SrcIP: net.IP(id.RemoteAddress),
SrcPort: id.RemotePort,
DstIP: net.IP(id.LocalAddress),
DstPort: id.LocalPort,
}
4 years ago
pc, err := proxy.DialUDP(metadata)
if err != nil {
log.Warnf("[UDP] dial %s: %v", metadata.DestinationAddress(), err)
4 years ago
return
}
metadata.MidIP, metadata.MidPort = parseAddr(pc.LocalAddr())
4 years ago
pc = newUDPTracker(pc, metadata)
defer pc.Close()
4 years ago
remote := metadata.Addr()
go handleUDPToRemote(uc, pc, remote)
handleUDPToLocal(uc, pc, remote)
}
func handleUDPToRemote(uc adapter.UDPConn, pc net.PacketConn, remote net.Addr) {
buf := pool.Get(pool.MaxSegmentSize)
defer pool.Put(buf)
4 years ago
for {
n, err := uc.Read(buf)
4 years ago
if err != nil {
return
}
if _, err := pc.WriteTo(buf[:n], remote); err != nil {
log.Warnf("[UDP] write to %s: %v", remote, err)
4 years ago
}
pc.SetReadDeadline(time.Now().Add(_udpSessionTimeout)) /* reset timeout */
4 years ago
log.Infof("[UDP] %s --> %s", uc.RemoteAddr(), remote)
4 years ago
}
}
func handleUDPToLocal(uc adapter.UDPConn, pc net.PacketConn, remote net.Addr) {
4 years ago
buf := pool.Get(pool.MaxSegmentSize)
4 years ago
defer pool.Put(buf)
for {
pc.SetReadDeadline(time.Now().Add(_udpSessionTimeout))
4 years ago
n, from, err := pc.ReadFrom(buf)
if err != nil {
if !errors.Is(err, os.ErrDeadlineExceeded) /* ignore I/O timeout */ {
log.Warnf("[UDP] read from %s: %v", pc.LocalAddr(), err)
4 years ago
}
return
}
if from == nil || from.Network() != remote.Network() || from.String() != remote.String() {
log.Warnf("[UDP] drop unknown packet from %v", from)
4 years ago
return
}
if _, err := uc.Write(buf[:n]); err != nil {
log.Warnf("[UDP] write back from %s: %v", from, err)
return
}
log.Infof("[UDP] %s <-- %s", uc.RemoteAddr(), from)
4 years ago
}
}