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.

144 lines
3.2 KiB

4 years ago
package tunnel
import (
"errors"
"net"
"os"
"strconv"
"time"
4 years ago
"github.com/xjasonlyu/tun2socks/common/pool"
"github.com/xjasonlyu/tun2socks/component/nat"
M "github.com/xjasonlyu/tun2socks/constant"
"github.com/xjasonlyu/tun2socks/core"
4 years ago
"github.com/xjasonlyu/tun2socks/log"
"github.com/xjasonlyu/tun2socks/proxy"
"github.com/xjasonlyu/tun2socks/tunnel/statistic"
4 years ago
)
const (
udpSessionTimeout = 60 * time.Second
4 years ago
)
var (
// _natTable uses source udp packet information
4 years ago
// as key to store destination udp packetConn.
_natTable = nat.NewTable()
4 years ago
)
func newUDPTracker(conn net.PacketConn, metadata *M.Metadata) net.PacketConn {
return statistic.NewUDPTracker(conn, metadata, statistic.DefaultManager)
}
func handleUDP(packet core.UDPPacket) {
id := packet.ID()
metadata := &M.Metadata{
Net: M.UDP,
SrcIP: net.IP(id.RemoteAddress),
SrcPort: id.RemotePort,
DstIP: net.IP(id.LocalAddress),
DstPort: id.LocalPort,
}
4 years ago
generateNATKey := func(m *M.Metadata) string {
return m.SourceAddress() /* as Full Cone NAT Key */
4 years ago
}
key := generateNATKey(metadata)
handle := func(drop bool) bool {
pc := _natTable.Get(key)
4 years ago
if pc != nil {
handleUDPToRemote(packet, pc, metadata /* as net.Addr */, drop)
return true
}
return false
}
if handle(true /* drop */) {
return
}
lockKey := key + "-lock"
cond, loaded := _natTable.GetOrCreateLock(lockKey)
4 years ago
go func() {
if loaded {
cond.L.Lock()
cond.Wait()
handle(true) /* drop after sending data to remote */
cond.L.Unlock()
return
}
defer func() {
_natTable.Delete(lockKey)
4 years ago
cond.Broadcast()
}()
pc, err := proxy.DialUDP(metadata)
if err != nil {
log.Warnf("[UDP] dial %s error: %v", metadata.DestinationAddress(), err)
return
}
if dialerAddr, ok := pc.LocalAddr().(*net.UDPAddr); ok {
metadata.MidIP = dialerAddr.IP
metadata.MidPort = uint16(dialerAddr.Port)
4 years ago
} else { /* fallback */
4 years ago
ip, p, _ := net.SplitHostPort(pc.LocalAddr().String())
port, _ := strconv.ParseUint(p, 10, 16)
metadata.MidIP = net.ParseIP(ip)
metadata.MidPort = uint16(port)
}
4 years ago
pc = newUDPTracker(pc, metadata)
4 years ago
go func() {
defer pc.Close()
defer packet.Drop()
defer _natTable.Delete(key)
4 years ago
4 years ago
handleUDPToLocal(packet, pc, udpSessionTimeout)
4 years ago
}()
_natTable.Set(key, pc)
4 years ago
handle(false /* drop */)
}()
}
func handleUDPToRemote(packet core.UDPPacket, pc net.PacketConn, remote net.Addr, drop bool) {
4 years ago
defer func() {
if drop {
packet.Drop()
}
}()
if _, err := pc.WriteTo(packet.Data() /* data */, remote); err != nil {
log.Warnf("[UDP] write to %s error: %v", remote, err)
}
log.Infof("[UDP] %s --> %s", packet.RemoteAddr(), remote)
}
func handleUDPToLocal(packet core.UDPPacket, pc net.PacketConn, timeout time.Duration) {
4 years ago
buf := pool.Get(pool.MaxSegmentSize)
4 years ago
defer pool.Put(buf)
for /* just loop */ {
pc.SetReadDeadline(time.Now().Add(timeout))
n, from, err := pc.ReadFrom(buf)
if err != nil {
if !errors.Is(err, os.ErrDeadlineExceeded) /* ignore i/o timeout */ {
4 years ago
log.Warnf("[UDP] read error: %v", err)
4 years ago
}
return
}
if _, err := packet.WriteBack(buf[:n], from); err != nil {
log.Warnf("[UDP] write back from %s error: %v", from, err)
return
}
log.Infof("[UDP] %s <-- %s", packet.RemoteAddr(), from)
}
}