chore: move sing-tun's udpTimeout fix to there lib

This commit is contained in:
wwqgtxx
2023-03-23 19:53:28 +08:00
parent a7944f1369
commit 291b5be986
3 changed files with 19 additions and 36 deletions

View File

@ -3,7 +3,6 @@ package sing
import (
"context"
"errors"
"go.uber.org/atomic"
"golang.org/x/exp/slices"
"net"
"net/netip"
@ -15,7 +14,6 @@ import (
"github.com/Dreamacro/clash/log"
"github.com/Dreamacro/clash/transport/socks5"
tun "github.com/metacubex/sing-tun"
vmess "github.com/sagernet/sing-vmess"
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
@ -99,23 +97,11 @@ func (h *ListenerHandler) NewPacketConnection(ctx context.Context, conn network.
defer mutex.Unlock()
conn2 = nil
}()
lastWrite := atomic.NewTime(time.Now())
needTimeout := tun.NeedTimeoutFromContext(ctx) // gvisor stack call NewPacketConnection() with ContextWithNeedTimeout()
udpTimeout := h.UDPTimeout
if udpTimeout == 0 {
udpTimeout = UDPTimeout
}
for {
buff := buf.NewPacket() // do not use stack buffer
if needTimeout {
_ = conn.SetReadDeadline(time.Now().Add(udpTimeout))
}
dest, err := conn.ReadPacket(buff)
if err != nil {
buff.Release()
if needTimeout && E.IsTimeout(err) && time.Now().Sub(lastWrite.Load()) < udpTimeout {
continue // someone write successful in time, so we continue read instead of return error
}
if E.IsClosed(err) {
break
}
@ -123,12 +109,11 @@ func (h *ListenerHandler) NewPacketConnection(ctx context.Context, conn network.
}
target := socks5.ParseAddr(dest.String())
packet := &packet{
conn: &conn2,
mutex: &mutex,
rAddr: metadata.Source.UDPAddr(),
lAddr: conn.LocalAddr(),
buff: buff,
lastWrite: lastWrite,
conn: &conn2,
mutex: &mutex,
rAddr: metadata.Source.UDPAddr(),
lAddr: conn.LocalAddr(),
buff: buff,
}
select {
case h.UdpIn <- inbound.NewPacket(target, packet, h.Type, additions...):
@ -143,12 +128,11 @@ func (h *ListenerHandler) NewError(ctx context.Context, err error) {
}
type packet struct {
conn *network.PacketConn
mutex *sync.Mutex
rAddr net.Addr
lAddr net.Addr
buff *buf.Buffer
lastWrite *atomic.Time
conn *network.PacketConn
mutex *sync.Mutex
rAddr net.Addr
lAddr net.Addr
buff *buf.Buffer
}
func (c *packet) Data() []byte {
@ -179,7 +163,6 @@ func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
if err != nil {
return
}
c.lastWrite.Store(time.Now())
return
}