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

tcp_fast_open in direct outbound silently breaks connections when domains are resolved via route action instead of domain_resolver

Open kjdtw6wtgt-ai opened this issue 3 months ago • 2 comments

Operating system

Linux

System version

Ubuntu 24.04.4 LTS, kernel: 6.8.0-137-generic

Installation type

Original sing-box Command Line

If you are using a graphical client, please provide the version of the client.

No response

Version

sing-box version 1.13.16

Environment: go1.25.12 linux/amd64
Tags: with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,with_naive_outbound,badlinkname,tfogo_checklinkname0,with_musl
Revision: 17ec3c71af8ca946dc50bf0d927c39fc77322aec
CGO: enabled

Description

When a domain is resolved by a route rule action ({"action": "resolve"}) instead of the outbound's own domain_resolver, and the direct outbound has tcp_fast_open: true, outbound connections fail silently.

The connection is dialed, then immediately closed within 1ms, with no error logged at any log level (tested with "level": "trace"). The client keeps retrying, and every attempt fails the same way.

From the application's point of view this is not a clean failure — some pages load partially with broken layout, and some fail with TLS integrity errors ("connection is not secure"), which suggests data corruption rather than a plain connection failure.

Only one of the four possible combinations is affected:

domain resolution tcp_fast_open result
route action: resolve true BROKEN
route action: resolve false works
outbound domain_resolver true works
outbound domain_resolver false works

Adding "strategy": "ipv4_only" to the resolve action also fixes it, which suggests the problem is related to handling multiple resolved addresses. The affected domains resolve to many addresses at once (8 for github.githubassets.com, 16 for signaler-pa.googleapis.com).

Log comparison from the same server, same domains, same session length:

without strategy: 28 outbound connections, 30 "download closed", 0 "download finished", 0 ERROR lines with ipv4_only: 20 outbound connections, 2 "download closed", 1 "download finished"

Reproduced on two servers: one with working IPv6 connectivity and one without. On the server without IPv6, an explicit error is logged ("dial tcp [...]:443: connect: network is unreachable" followed by "write handshake failure: invalid argument"). On the server with working IPv6, the failure is completely silent — no error at all.

Expected: connections should either succeed, or fail with a logged error and fall back to another resolved address — the same way they do when the domain is resolved via domain_resolver.

Reproduction

  1. Confirm TCP Fast Open is enabled in the kernel:
sysctl net.ipv4.tcp_fastopen
# net.ipv4.tcp_fastopen = 3
  1. Start sing-box with the config below.

  2. Connect any Hysteria2 client and open a website that resolves to multiple A and AAAA records, e.g. github.githubassets.com or signaler-pa.googleapis.com.

    Connections fail. In the log each connection is dialed and closed within 1ms, with no error logged even at trace level:

    INFO outbound/direct[direct]: outbound connection to github.githubassets.com:443 DEBUG connection: connection upload finished TRACE connection: connection download closed

  3. Remove "tcp_fast_open": true from the direct outbound. Restart, repeat step 3 — everything works.

  4. Restore "tcp_fast_open": true. Remove the resolve rule from route.rules and add "domain_resolver": "dns-local" to the direct outbound instead. Restart, repeat step 3 — everything works.

  5. Restore the resolve rule, changing it to:

    { "action": "resolve", "strategy": "ipv4_only" }

    Restart, repeat step 3 — everything works.

Only the combination in steps 1-3 fails. The same behaviour was observed with a VLESS inbound instead of Hysteria2.

Note: the target domains have to be real ones with multiple A and AAAA records, so this part cannot be reproduced purely on loopback.

{
  "log": {
    "level": "trace",
    "timestamp": true,
    "disabled": false
  },
  "dns": {
    "servers": [
      {
        "type": "local",
        "tag": "dns-local"
      }
    ]
  },
  "inbounds": [
    {
      "type": "hysteria2",
      "tag": "hy2-in",
      "listen": "::",
      "listen_port": 443,
      "users": [
        {
          "name": "test",
          "password": "PLACEHOLDER_PASSWORD"
        }
      ],
      "ignore_client_bandwidth": false,
      "tls": {
        "enabled": true,
        "server_name": "example.com",
        "alpn": [
          "h3"
        ],
        "certificate_path": "/etc/sing-box/cert.pem",
        "key_path": "/etc/sing-box/key.pem"
      },
      "masquerade": {
        "type": "proxy",
        "url": "https://example.com",
        "rewrite_host": true
      }
    }
  ],
  "outbounds": [
    {
      "type": "direct",
      "tag": "direct",
      "tcp_fast_open": true
    }
  ],
  "route": {
    "rules": [
      {
        "action": "resolve"
      }
    ],
    "default_domain_resolver": "dns-local",
    "final": "direct"
  }
}

Logs

### Broken: `action: resolve` (no strategy) + `tcp_fast_open: true`

Server with working IPv6 connectivity. The connection is dialed and closed
within 1 ms. No ERROR line is produced anywhere in the session, even at
trace level:

2026-08-04 22:48:25 INFO  [2381974972] inbound/vless[vless-in]: inbound connection to signaler-pa.googleapis.com:443
2026-08-04 22:48:25 DEBUG [2381974972] router: match[4] => resolve
2026-08-04 22:48:25 DEBUG [2381974972] dns: lookup domain signaler-pa.googleapis.com
2026-08-04 22:48:25 DEBUG [2381974972] dns: match[1] clash_mode=direct => route(dns-local)
2026-08-04 22:48:25 INFO  [2381974972] dns: lookup succeed for signaler-pa.googleapis.com: 172.217.115.4 172.217.118.4 172.217.114.4 172.217.116.4 172.217.112.4 172.217.113.4 172.217.119.4 172.217.117.4 2001:4860:4846:400:: 2001:4860:4843:400:: 2001:4860:4844:400:: 2001:4860:4841:400:: 2001:4860:4840:400:: 2001:4860:4847:400:: 2001:4860:4842:400:: 2001:4860:4845:400::
2026-08-04 22:48:25 DEBUG [2381974972] router: resolved [172.217.115.4 ... 2001:4860:4845:400::]
2026-08-04 22:48:25 DEBUG [2381974972] router: match[5] clash_mode=direct => route(direct)
2026-08-04 22:48:25 INFO  [2381974972] outbound/direct[direct]: outbound connection to signaler-pa.googleapis.com:443
2026-08-04 22:48:25 DEBUG [2381974972] connection: connection upload finished
2026-08-04 22:48:25 TRACE [2381974972] connection: connection download closed

The client retries roughly every 100 ms and every attempt ends the same way.

### Same setup on a server without IPv6 connectivity

Here the failure is not silent — an error is logged, which may be a hint
about what goes wrong in the silent case as well:

dial tcp [REDACTED]:443: connect: network is unreachable
write handshake failure: invalid argument

### Working: `action: resolve` with `"strategy": "ipv4_only"`

Same server, same domains, everything else unchanged:

2026-08-04 22:46:12 INFO  [2151096158] inbound/vless[vless-in]: inbound connection to ipv6a.cloudflare-dns.com:443
2026-08-04 22:46:12 DEBUG [2151096158] router: match[4] => resolve(ipv4_only)
2026-08-04 22:46:12 DEBUG [2151096158] dns: lookup domain ipv6a.cloudflare-dns.com
2026-08-04 22:46:12 DEBUG [2151096158] dns: match[1] clash_mode=direct => route(dns-local)
2026-08-04 22:46:12 DEBUG [2151096158] dns: exchanged ipv6a.cloudflare-dns.com NOERROR 1800

(The `lookup failed: empty result` lines for ipv6a/ipv6b.cloudflare-dns.com
that appear in this log are expected — those hostnames are AAAA-only, so
ipv4_only correctly returns nothing for them. They are unrelated to the bug.)

### Summary, same server and comparable session length

  action: resolve (no strategy)   28 outbound connections
                                  30 "connection download closed"
                                   0 "connection download finished"
                                   0 ERROR lines

  action: resolve + ipv4_only     20 outbound connections
                                   2 "connection download closed"
                                   1 "connection download finished"

Note: the logs above were captured on my production config, which has
additional routing rules and clash_mode — hence match[4]/match[5] instead
of match[0]. The relevant part (action: resolve → outbound/direct with
tcp_fast_open) is identical to the minimal config above.

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.

kjdtw6wtgt-ai avatar Aug 04 '26 23:08 kjdtw6wtgt-ai

Another tcp_fast_open failure on 1.14.0, different code path — leaving it here in case it shares a root cause.

tcp_fast_open: true on a direct outbound breaks StartNetworkQualityTest via the new API service, while the very same config works through sing-box tools network quality.

{ "log": { "level": "warn" }, "dns": { "servers": [{ "type": "local", "tag": "l" }], "final": "l" }, "outbounds": [ { "type": "direct", "tag": "direct", "tcp_fast_open": true, "domain_resolver": "l" } ], "services": [ { "type": "api", "tag": "api-test", "listen": "127.0.0.1", "listen_port": 9099, "dashboard": false } ], "route": { "final": "direct", "default_domain_resolver": "l" } }

sing-box run -c tfo-api.json grpcurl -plaintext -d '{"outboundTag":"direct","maxRuntimeSeconds":20}'
127.0.0.1:9099 daemon.StartedService/StartNetworkQualityTest

{ "isFinal": true, "error": "fetch config: Get "https://mensura.cdn-apple.com/api/v1/gm/config": dial tcp 17.253.39.131:443: operation was canceled" }

Verified:

same config with "tcp_fast_open": false → test completes normally same config with tcp_fast_open: true via sing-box tools networkquality → completes normally

So the dialer itself is fine; only the API service's outgoing request path fails.

sing-box 1.14.0, Linux amd64, net.ipv4.tcp_fastopen = 3.

Also reproducible through the dashboard's network quality test UI (same API path).

kjdtw6wtgt-ai avatar Sep 02 '26 01:09 kjdtw6wtgt-ai

I think the four-way reproduction matrix has a deterministic explanation in the v1.13.16 source, and the same lifetime problem still exists in current testing.

The core issue is not only "TFO + multiple resolved addresses". It is that the mixed-family parallel dialer treats a lazy TFO connection object as an already-established connection and then cancels the context that the lazy connection still needs.

1. route resolve changes the connection path

When the route resolve action has already populated:

metadata.DestinationAddresses

ConnectionManager.NewConnection() takes this branch:

if len(metadata.DestinationAddresses) > 0 ||
    metadata.Destination.IsIP() {

    remoteConn, err = dialer.DialSerialNetwork(
        ctx,
        this,
        N.NetworkTCP,
        metadata.Destination,
        metadata.DestinationAddresses,
        ...
    )
} else {
    remoteConn, err =
        this.DialContext(ctx, N.NetworkTCP, metadata.Destination)
}

The direct outbound implements ParallelNetworkDialer, so for a mixed A+AAAA result this ultimately enters DialParallelNetwork().

2. The parallel racer owns a temporary child context

The mixed-family path does roughly:

primaryCtx, primaryCancel := context.WithCancel(ctx)
defer primaryCancel()

go startRacer(primaryCtx, true)

and as soon as a racer reports:

res.error == nil

the connection is returned.

For an ordinary TCP dial that is fine: by this point the connect operation has actually completed.

For the current TFO implementation that assumption is false.

3. TFO DialSlowContext() does not dial yet

With TCP Fast Open enabled:

func DialSlowContext(
    dialer *tfo.Dialer,
    ctx context.Context,
    network string,
    destination M.Socksaddr,
) (net.Conn, error) {
    ...

    return &slowOpenConn{
        dialer:      dialer,
        ctx:         ctx,
        network:     network,
        destination: destination,
        ...
    }, nil
}

There is no TCP connection here yet.

The real operation happens later in the first Write():

conn, err := c.dialer.DialContext(
    c.ctx,
    c.network,
    c.destination.String(),
    b,
)

Therefore the failing sequence is:

route resolve
    ↓
mixed A + AAAA DestinationAddresses
    ↓
DialParallelNetwork
    ↓
primaryCtx := context.WithCancel(parent)
    ↓
DialSlowContext(primaryCtx)
    ↓
returns slowOpenConn immediately
(no TCP connect has happened)
    ↓
parallel racer sees err == nil
    ↓
declares this connection the winner
    ↓
DialParallelNetwork returns it
    ↓
deferred primaryCancel()
    ↓
primaryCtx is now cancelled
    ↓
first Write()
    ↓
tfo.DialContext(primaryCtx, ...)
    ↓
dial starts with an already-cancelled context

So the race is effectively completed before the thing being raced has actually happened.

4. This explains the reporter's complete matrix

route resolve + tcp_fast_open=true

Broken.

Pre-resolved mixed-family addresses enter DialParallelNetwork(), while TFO returns a lazy connection carrying the racer's temporary context.

route resolve + tcp_fast_open=false

Works.

Without TFO, the real TCP connect completes before the racer reports success. Cancelling that dial context after an established connection has been returned does not invalidate the socket.

domain_resolver + tcp_fast_open=true

Works because there is already an explicit safeguard for this case.

NewWithOptions() constructs the resolver as:

NewResolveDialer(
    ...,
    dialOptions.Detour == "" &&
        !dialOptions.TCPFastOpen,
    ...
)

So when TFO is enabled:

parallel = false

and resolveDialer.DialContext() uses:

N.DialSerial(...)

The slowOpenConn therefore keeps the original connection context rather than a temporary Happy-Eyeballs racer context.

route resolve + ipv4_only + tcp_fast_open=true

Also works for the same reason.

DialParallelNetwork() detects that only one address family exists and immediately falls back to:

DialSerialNetwork(ctx, ...)

using the original parent context.

No primaryCtx racer is created, so there is nothing to cancel before the TFO first write.

This makes the ipv4_only workaround particularly strong evidence for the lifetime bug.

5. Why the failure can be silent

There also appears to be a secondary observability issue.

DefaultDialer.trackConn() wraps successful connections using:

connectionManager.TrackConn(conn)

and the resulting trackedConn exposes its underlying connection through:

func (c *trackedConn) Upstream() any {
    return c.Conn
}

slowOpenConn, however, currently advertises its deferred handshake using the legacy:

func (c *slowOpenConn) NeedHandshake() bool

NeedHandshakeForWriteAny() checks that legacy EarlyConn interface with a direct type assertion.

Its recursive common.Cast()/Upstream() path is used for EarlyWriter, not for that legacy EarlyConn check.

So after slowOpenConn has been wrapped in trackedConn, kickWriteHandshake() can fail to see that the TFO connection still needs its first-write handshake.

The actual failure then occurs later inside the normal connection copy path.

That path deliberately treats closed/cancelled errors as non-error shutdowns and logs them only at TRACE, which matches the report's:

connection upload finished
connection download closed

without an ERROR line.

A useful secondary cleanup would therefore be for slowOpenConn to expose the current write-handshake interface, e.g. conceptually:

func (c *slowOpenConn) NeedHandshakeForWrite() bool {
    return c.conn.Load() == nil
}

so the handshake state remains discoverable through wrappers.

That improves error propagation, but it does not fix the primary problem: forcing the write after the racer has already cancelled its context would merely turn the silent failure into an explicit failure.

Suggested primary fix

I think the lowest-risk fix is to make pre-resolved TFO follow the same policy that NewResolveDialer() already uses:

do not perform mixed-family parallel racing on a connection whose actual dial is deferred until first write.

For the direct outbound, conceptually:

pre-resolved addresses
        +
TCP Fast Open / slow-open
        ↓
serial address path

instead of:

pre-resolved A + AAAA
        ↓
Happy-Eyeballs child contexts
        ↓
lazy TFO connections

This restores parity between:

route action: resolve

and:

outbound domain_resolver

without trying to make the generic Happy-Eyeballs implementation understand an operation that has not completed yet.

A more general solution is possible, but then the definition of "winner" has to change.

For a deferred connection:

DialContext() returned object

cannot mean:

transport established successfully

and the winning racer's child context must remain alive until the deferred handshake completes or the connection is closed.

There is also a separate question about fallback: if the first TFO address only fails during the first write, the existing serial slow-open path cannot try the next resolved address at dial time. That may deserve a separate handshake-aware retry design rather than being mixed into this fix.

Regression tests

A deterministic unit test does not need real IPv6 or TFO support.

A fake lazy dialer can:

  1. capture the context passed by the racer;
  2. return a net.Conn immediately with nil error;
  3. defer checking that context until its first Write().

Then:

DialParallelNetwork(
    IPv4 + IPv6 addresses
)

must never return a successful lazy connection whose captured context is already cancelled.

I would also cover:

  • route resolve + mixed A/AAAA + TFO;
  • route resolve + ipv4_only + TFO;
  • domain_resolver + TFO;
  • normal non-TFO Happy-Eyeballs remains parallel;
  • losing racers are still cancelled/closed;
  • parent connection cancellation still cancels an unfinished slow-open;
  • a tracked slowOpenConn still reports that it needs a write handshake;
  • first-write failure behavior across multiple resolved addresses is explicitly defined.

I don't see the lifetime issue fixed in current testing.

The post-issue change:

93df3ef61208ab449bd60bb2bc0479b37f06adf5
Fix slow open connection declaring lazy headroom

only removes slowOpenConn.LazyHeadroom(); it does not change the stored context or the parallel-racer cancellation behavior.

So I would classify #4386 as:

Happy-Eyeballs declares a lazy TFO connection successful before transport establishment, then cancels the winning dial context before the deferred first-write dial occurs.

HeisLuka avatar Sep 09 '26 20:09 HeisLuka