sing-box icon indicating copy to clipboard operation
sing-box copied to clipboard

UDP listener of direct inbound is closed at startup on armv7 (kernel 4.1.52): recvmmsg: function not implemented

Open abcfy2 opened this issue 2 months ago • 2 comments

Operating system

Linux

System version

ASUS TUF-AX5400 router, ASUSWRT-Merlin firmware Linux 4.1.52 (armv7l, 32-bit)

Installation type

Original sing-box Command Line

Version

sing-box version 1.14.0

Environment: go1.26.7 linux/arm
Tags: with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,with_cloudflared,with_usbip,with_openvpn,with_openconnect,badlinkname,tfogo_checklinkname0
Revision: 0b8995879f29a9b98ee027bc17b75e101445b238
CGO: disabled

(unmodified official release: sing-box-1.14.0-linux-armv7.tar.gz)

Description

On this device, the UDP listener of a direct inbound is closed immediately at startup; only the TCP listener remains (verified with netstat). The same happens with the documented hijack-dns setup (direct "dns-in" inbound + route rule {"inbound":["dns-in"],"action":"hijack-dns"}).

Result: transparent DNS hijack via iptables REDIRECT (udp dport 53 -> the direct inbound) stops working for LAN clients - UDP DNS gets no response, so the whole network loses UDP DNS while TCP keeps working.

Reproduction

  1. Unpack sing-box-1.14.0-linux-armv7.tar.gz on the device (kernel 4.1.52, armv7l).
  2. Run: sing-box run -c config.json
  3. netstat -lnt shows TCP :1054 LISTEN; netstat -lnu shows no UDP :1054 socket.

config.json (complete, minimal, no TUN / no remote server):

{
  "log": { "level": "warn" },
  "inbounds": [
    { "type": "direct", "tag": "dns-in", "listen": "::", "listen_port": 1054 }
  ],
  "outbounds": [ { "type": "direct", "tag": "d" } ]
}

The documented hijack-dns configuration pattern (direct dns-in inbound + route rule {"inbound":["dns-in"],"action":"hijack-dns"}, dns server type local) produces the same result on port 1055.

Logs

# uname -a
Linux TUF-AX5400-0368 4.1.52 #1 SMP PREEMPT Wed Jun 10 00:57:46 UTC 2026 armv7l ASUSWRT-Merlin

# sing-box run -c config.json
ERROR[0000] inbound/direct[dns-in]: udp listener closed: raw read: recvmmsg: function not implemented

# netstat -lnt | grep 1054
tcp        0      0 :::1054                 :::*                    LISTEN

# netstat -lnu | grep 1054
(no output)

Supporter

Integrity requirements

  • [x] I confirm that I have read the documentation, understand the meaning of all the configuration items I wrote, and did not pile up seemingly useful options or default values.
  • [x] I confirm that I have provided the server and client configuration files and process that can be reproduced locally, instead of a complicated client configuration file that has been stripped of sensitive data.
  • [x] I confirm that I have provided the simplest configuration that can be used to reproduce the error I reported, instead of depending on remote servers, TUN, graphical interface clients, or other closed-source software.
  • [x] I confirm that I have provided the complete configuration files and logs, rather than just providing parts I think are useful out of confidence in my own intelligence.

abcfy2 avatar Sep 05 '26 13:09 abcfy2

I traced this through v1.13.0, v1.14.0, the current testing branch, and the corresponding sagernet/sing batch I/O implementation.

This looks like a deterministic v1.14 UDP batch capability regression, rather than simply "Linux 4.1 is too old".

Regression point

In v1.13.0, common/listener/listener_udp.go used the scalar UDP path:

n, addr, err := l.udpConn.ReadFromUDPAddrPort(...)

and replies were written with:

l.udpConn.WriteToUDPAddrPort(...)

Commit:

2bbff23640fdb7fcb445267bc8467970127f31d6
Improve UDP batch support

changed this behavior before the v1.14.0 release.

A direct inbound now implements:

func (i *Inbound) NewPacketBatch(
    buffers []*buf.Buffer,
    sources []M.Socksaddr,
) {
    i.udpNat.NewPacketBatch(
        buffers,
        sources,
        i.listener.UDPAddr(),
        nil,
    )
}

so it satisfies adapter.PacketBatchHandler.

Listener.loopUDPIn() consequently tries the batch reader automatically:

if l.oobPacketHandler == nil {
    if batchHandler, isBatchHandler :=
        l.packetHandler.(adapter.PacketBatchHandler); isBatchHandler {

        packetConn := sBufio.NewPacketConn(l.udpConn)

        if readWaiter, created :=
            sBufio.CreatePacketBatchReadWaiter(packetConn); created {

            l.loopUDPInBatch(batchHandler, readWaiter)
            return
        }
    }
}

On Linux, sagernet/sing/common/bufio/packet_batch_mmsg.go decides that this syscall batch waiter is available from the socket/RawConn shape:

func createSyscallPacketBatchReadWaiter(
    reader any,
) (N.PacketBatchReadWaiter, bool) {
    rawConn := syscallPacketBatchRawConnForRead(reader)
    if rawConn == nil {
        return nil, false
    }

    ...

    return &syscallPacketBatchReadWaiter{
        rawConn: rawConn,
    }, true
}

There is no runtime recvmmsg capability check here.

The actual read later executes:

w.readN, errno = recvmmsg(
    int(fd),
    w.msgvec,
    0,
)

and an unsupported syscall becomes:

w.readErr =
    os.NewSyscallError("recvmmsg", errno)

which propagates as:

raw read: recvmmsg: function not implemented

Then sing-box does:

buffers, sources, err :=
    readWaiter.WaitReadPackets()

if err != nil {
    ...
    l.udpConn.Close()
    l.logger.Error("udp listener closed: ", err)
    return
}

So the reporter's exact observation is explained:

recvmmsg -> ENOSYS
    -> WaitReadPackets error
    -> loopUDPInBatch treats it as fatal
    -> UDP socket is closed

The ordinary scalar UDP path immediately below this code would work, but it is never reached after the batch waiter has been successfully created.

This is still present in current testing

Current sing-box testing still uses the automatic batch listener path and currently depends on:

github.com/sagernet/sing
v0.9.4-0.20260909041121-b9fce5efdd99

The current packet_batch_mmsg.go still performs the raw recvmmsg syscall without an ENOSYS downgrade.

So I do not see this fixed in the current testing source.

Linux 4.1 itself does not seem to be the correct capability test

One detail worth separating from the application bug:

the public ASUSWRT-Merlin Linux 4.1 ARM source actually contains:

__NR_recvmmsg = __NR_SYSCALL_BASE + 365

and the ARM syscall table maps slot 365 to:

CALL(sys_recvmmsg)

The kernel source also contains the recvmmsg syscall implementation.

Therefore I don't think the fix should be based on:

kernel < X -> disable recvmmsg

I cannot determine from static source why this exact running ASUS firmware returns ENOSYS — it could be a different vendor build/configuration or another firmware-specific restriction.

But that distinction does not change the sing-box/sing failure mode: an optional batch-I/O optimization being unavailable should not destroy UDP service.

sendmmsg should be handled at the same time

There is a symmetric issue on the output path.

v1.14 loopUDPOut() now uses:

packetConn := sBufio.NewPacketConn(l.udpConn)
batchWriter := sBufio.NewPacketBatchWriter(packetConn)

On Linux, if a RawConn is available, CreatePacketBatchWriter() selects the syscall writer, which eventually performs:

sendmmsg(...)

There is already a perfectly usable:

fallbackPacketBatchWriter

which sends the packets one by one.

But NewPacketBatchWriter() only selects that fallback if batch writer creation returns false.

If sendmmsg is selected successfully and then returns ENOSYS at runtime, it just returns an error; it does not downgrade.

So fixing only recvmmsg could leave this environment able to receive UDP while still failing to send replies if its sendmmsg syscall is also unavailable.

Suggested fix boundary

I think the clean fix belongs in:

SagerNet/sing/common/bufio

rather than as a special case in the sing-box direct inbound.

The invariant should be:

recvmmsg / sendmmsg are performance optimizations. Runtime unavailability must downgrade to normal packet I/O, not affect connection liveness.

Two possible implementations:

  1. Probe syscall availability once and cache it. If the syscall returns ENOSYS, make createSyscallPacketBatchReadWaiter() / createSyscallPacketBatchWriter() report unsupported, allowing the existing scalar fallback paths to be selected.

  2. Alternatively, detect ENOSYS on first use inside the syscall waiter/writer and permanently downgrade that instance to scalar I/O.

I would prefer capability detection/fallback over a kernel-version check, because the public 4.1 ARM source already demonstrates that version alone does not describe syscall availability.

Regression tests

It would be useful to have test seams around recvmmsg/sendmmsg so ENOSYS can be injected without an actual old/vendor kernel.

Cases I would cover:

  1. recvmmsg -> ENOSYS:

    • batch optimization is disabled/downgraded;
    • UDP listener remains open;
    • subsequent datagrams are received through scalar I/O.
  2. sendmmsg -> ENOSYS:

    • output downgrades to scalar WritePacket;
    • UDP replies continue working.
  3. EAGAIN / EWOULDBLOCK must remain normal readiness conditions and must not disable batching.

  4. The packet which triggers the downgrade must not be lost or duplicated.

  5. On a supported kernel, the existing recvmmsg / sendmmsg fast path remains in use.

  6. A direct inbound used for:

{
    "inbound": ["dns-in"],
    "action": "hijack-dns"
}

must continue serving UDP when the batch syscalls are unavailable.

So my current classification would be:

v1.14 introduced mandatory-at-runtime Linux mmsg behavior for UDP paths that previously used scalar socket I/O; ENOSYS is currently treated as a fatal socket error instead of a capability miss.

HeisLuka avatar Sep 09 '26 20:09 HeisLuka

Thanks @HeisLuka for the deep trace — the failure-mode analysis is exactly right. The missing piece is one layer below: the shipped binary never called the classic recvmmsg at all.

Why ENOSYS on a kernel that has recvmmsg

sing-box 1.14.0 pins sagernet/sing v0.9.0-beta.4, which contained common/bufio/packet_batch_mmsg_linux32.go:

//go:build linux && (386 || arm || mips || mipsle || ppc)

const sysRecvmmsg = unix.SYS_RECVMMSG_TIME64

On 32-bit Linux this overrides the syscall number with the TIME64 variant, which only exists since kernel 5.1 — so 4.1.52 returns ENOSYS. The classic recvmmsg (slot 365) you found in the public 4.1 source is never called by that build. This also answers why the kernel "isn't too old": the bug was specifically the TIME64 swap, not the kernel age.

The fix

Upstream fixed this right after the issue was filed:

  • sagernet/sing 372f2614 — "bufio: Fix packet batch read on 32-bit Linux before 5.1" (removes the linux32 TIME64 override, restores the classic syscall); included in sing v0.9.3
  • sing-box 0c041aa7 — "Fix direct inbound UDP on 32-bit Linux before 5.1" (bumps the dependency on testing)

So current testing is fixed at the root-cause level — the packet_batch_mmsg.go you read is the post-fix code. Your runtime-downgrade suggestion remains valid as hardening for exotic kernels (note sendmmsg was never affected here — it always used the classic syscall, present since 2.6.39).

Verified on the affected device

Tested the latest testing CI build (sing-box version 1.14.1, revision abc21e4b5, unmodified artifact) on the original device (Linux 4.1.52, armv7l):

  • minimal direct inbound (the repro config from this issue): starts clean, no error, UDP listener stays alive (netstat -lnu shows the socket; 1.14.0 drops it at startup)
  • hijack-dns setup: udp server started persists, and a real DNS query from a LAN client returns answers

@nekohasekai — with the fix confirmed working on the original affected device, could this issue be closed? Also, would you consider shipping it in a 1.14.x patch release? Every stable user on a 32-bit kernel < 5.1 currently has broken UDP for generic inbounds (transparent DNS hijack included).

abcfy2 avatar Sep 10 '26 02:09 abcfy2