Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: deliver UDP packets from same connection in receiving order #1540

Merged
merged 1 commit into from
Sep 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions tunnel/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"hash/maphash"
"net"
"net/netip"
"path/filepath"
Expand Down Expand Up @@ -31,7 +32,8 @@ import (
var (
status = newAtomicStatus(Suspend)
tcpQueue = make(chan C.ConnContext, 200)
udpQueue = make(chan C.PacketAdapter, 200)
udpQueues []chan C.PacketAdapter
udpHashSeed = maphash.MakeSeed()
natTable = nat.New()
rules []C.Rule
listeners = make(map[string]C.InboundListener)
Expand Down Expand Up @@ -70,8 +72,17 @@ func (t tunnel) HandleTCPConn(conn net.Conn, metadata *C.Metadata) {

func (t tunnel) HandleUDPPacket(packet C.UDPPacket, metadata *C.Metadata) {
packetAdapter := C.NewPacketAdapter(packet, metadata)

var h maphash.Hash

h.SetSeed(udpHashSeed)
h.WriteString(metadata.SourceAddress())
h.WriteString(metadata.RemoteAddress())

queueNo := uint(h.Sum64()) % uint(len(udpQueues))

select {
case udpQueue <- packetAdapter:
case udpQueues[queueNo] <- packetAdapter:
default:
}
}
Expand Down Expand Up @@ -141,7 +152,8 @@ func TCPIn() chan<- C.ConnContext {
// UDPIn return fan-in udp queue
// Deprecated: using Tunnel instead
func UDPIn() chan<- C.PacketAdapter {
return udpQueue
// compatibility: first queue is always available for external callers
return udpQueues[0]
}

// NatTable return nat table
Expand Down Expand Up @@ -243,8 +255,8 @@ func isHandle(t C.Type) bool {
}

// processUDP starts a loop to handle udp packet
func processUDP() {
queue := udpQueue
func processUDP(queueNo int) {
queue := udpQueues[queueNo]
for conn := range queue {
handleUDPConn(conn)
}
Expand All @@ -255,8 +267,11 @@ func process() {
if num := runtime.GOMAXPROCS(0); num > numUDPWorkers {
numUDPWorkers = num
}

udpQueues = make([]chan C.PacketAdapter, numUDPWorkers)
for i := 0; i < numUDPWorkers; i++ {
go processUDP()
udpQueues[i] = make(chan C.PacketAdapter, 200)
go processUDP(i)
}

queue := tcpQueue
Expand Down