Browse Source

Minor: improve tunnel/udp

pull/248/head
xjasonlyu 2 years ago
parent
commit
4cc02c822c
  1. 16
      tunnel/udp.go

16
tunnel/udp.go

@ -1,7 +1,6 @@
package tunnel package tunnel
import ( import (
"errors"
"io" "io"
"net" "net"
"sync" "sync"
@ -54,36 +53,31 @@ func handleUDPConn(uc adapter.UDPConn) {
pc = newSymmetricNATPacketConn(pc, metadata) pc = newSymmetricNATPacketConn(pc, metadata)
log.Infof("[UDP] %s <-> %s", metadata.SourceAddress(), metadata.DestinationAddress()) log.Infof("[UDP] %s <-> %s", metadata.SourceAddress(), metadata.DestinationAddress())
if err = pipePacket(uc, pc, remote); err != nil { pipePacket(uc, pc, remote)
log.Debugf("[UDP] %s <-> %s: %v", metadata.SourceAddress(), metadata.DestinationAddress(), err)
}
} }
func pipePacket(origin net.PacketConn, remote net.PacketConn, to net.Addr) error { func pipePacket(origin, remote net.PacketConn, to net.Addr) {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wg.Add(2) wg.Add(2)
var leftErr, rightErr error
go func() { go func() {
defer wg.Done() defer wg.Done()
if err := copyPacketData(remote, origin, to, _udpSessionTimeout); err != nil { if err := copyPacketData(remote, origin, to, _udpSessionTimeout); err != nil {
leftErr = errors.Join(leftErr, err) log.Debugf("[UDP] copy data for origin->remote: %v", err)
} }
}() }()
go func() { go func() {
defer wg.Done() defer wg.Done()
if err := copyPacketData(origin, remote, nil, _udpSessionTimeout); err != nil { if err := copyPacketData(origin, remote, nil, _udpSessionTimeout); err != nil {
rightErr = errors.Join(rightErr, err) log.Debugf("[UDP] copy data for remote->origin: %v", err)
} }
}() }()
wg.Wait() wg.Wait()
return errors.Join(leftErr, rightErr)
} }
func copyPacketData(dst net.PacketConn, src net.PacketConn, to net.Addr, timeout time.Duration) error { func copyPacketData(dst, src net.PacketConn, to net.Addr, timeout time.Duration) error {
buf := pool.Get(pool.MaxSegmentSize) buf := pool.Get(pool.MaxSegmentSize)
defer pool.Put(buf) defer pool.Put(buf)

Loading…
Cancel
Save