add buffer size option for udp connection

This commit is contained in:
ginuerzh
2025-07-30 21:40:53 +08:00
parent b64e5901b6
commit a5309eee97
26 changed files with 218 additions and 219 deletions
+7 -1
View File
@@ -10,8 +10,13 @@ import (
mdutil "github.com/go-gost/x/metadata/util"
)
const (
defaultBufferSize = 4096
)
type metadata struct {
udpTimeout time.Duration
udpTimeout time.Duration
udpBufferSize int
sniffing bool
sniffingUDP bool
@@ -34,6 +39,7 @@ type metadata struct {
func (h *tungoHandler) parseMetadata(md mdata.Metadata) (err error) {
h.md.udpTimeout = mdutil.GetDuration(md, "udpTimeout", "tungo.udpTimeout")
h.md.udpBufferSize = mdutil.GetInt(md, "udp.bufferSize", "udpBufferSize")
h.md.sniffing = mdutil.GetBool(md, "sniffing")
h.md.sniffingUDP = mdutil.GetBool(md, "sniffing.udp")
+22 -8
View File
@@ -6,13 +6,13 @@ import (
"context"
"crypto/tls"
"io"
"math"
"net"
"net/netip"
"strings"
"sync"
"time"
"github.com/go-gost/core/common/bufpool"
"github.com/go-gost/core/handler"
"github.com/go-gost/core/observer/stats"
"github.com/go-gost/core/recorder"
@@ -44,7 +44,8 @@ type transportHandler struct {
procCancel context.CancelFunc
// UDP session timeout.
udpTimeout time.Duration
udpTimeout time.Duration
udpBufferSize int
sniffing bool
sniffingUDP bool
@@ -344,33 +345,46 @@ func (h *transportHandler) handleUDPConn(uc adapter.UDPConn) {
t := time.Now()
log.Infof("%s <-> %s", remoteAddr, dstAddr)
pipePacketData(conn, cc, h.sniffingUDP, ro, h.udpTimeout)
h.pipePacketData(conn, cc, ro)
log.WithFields(map[string]any{
"duration": time.Since(t),
}).Infof("%s >-< %s", remoteAddr, dstAddr)
}
func pipePacketData(conn1, conn2 net.Conn, sniffing bool, ro *xrecorder.HandlerRecorderObject, timeout time.Duration) {
func (h *transportHandler) pipePacketData(conn1, conn2 net.Conn, ro *xrecorder.HandlerRecorderObject) {
timeout := h.udpTimeout
if timeout <= 0 {
timeout = udpSessionTimeout
}
bufferSize := h.udpBufferSize
if bufferSize <= 0 {
bufferSize = defaultBufferSize
}
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
copyPacketData(conn1, conn2, sniffing, false, ro, timeout)
buf := bufpool.Get(bufferSize)
defer bufpool.Put(buf)
copyPacketData(conn1, conn2, buf, h.sniffing, false, ro, timeout)
}()
go func() {
defer wg.Done()
copyPacketData(conn2, conn1, sniffing, true, ro, timeout)
buf := bufpool.Get(bufferSize)
defer bufpool.Put(buf)
copyPacketData(conn2, conn1, buf, h.sniffing, true, ro, timeout)
}()
wg.Wait()
}
func copyPacketData(dst, src net.Conn, sniffing bool, c2s bool, ro *xrecorder.HandlerRecorderObject, timeout time.Duration) error {
buf := make([]byte, math.MaxUint16/2)
func copyPacketData(dst, src net.Conn, buf []byte, sniffing bool, c2s bool, ro *xrecorder.HandlerRecorderObject, timeout time.Duration) error {
isDNS := false
for {