net: only monitor select exceptions while connecting #36716

Manually merged
Sjors merged 1 commit from 2026/10/windows-select-exceptions into master 2026-11-26 14:04:51 +00:00 AGit
Sjors commented 2026-10-31 04:13:49 +00:00 (Migrated from github.com)

Alternative approach to #36688, citing the relevant parts of its description:

There is currently nothing preventing us to receive TCP urgent data, which would never be returned by recv(). Linux's poll() is indifferent to this, but the select() socket monitoring may keep reporting it as pending on some platforms.

This would not prevent progress nor lead to a crash anymore after #36665, but it's still undesirable.

Fix this by only adding a socket to the select() exception set while waiting for a non-blocking connect() to complete. Windows needs that to detect a failed connection. Established connections no longer monitor the exception set on any platform. This approach was suggested by theuni in https://github.com/bitcoin/bitcoin/pull/36716#issuecomment-6931290348.

To opt in, ErrorEvent can now be requested from Sock::Wait(), like RecvEvent and SendEvent. With select() that adds the socket to the exception set. ConnectToSocket() is the only caller that requests it. There is no behavior change with poll(), which reports errors whether or not they are requested. Using ErrorEvent for this was suggested by vasild in https://github.com/bitcoin/bitcoin/pull/36716#discussion_r4692637894.

We could instead have set SO_OOBINLINE on our sockets, so recv() returns any urgent data sent to us (and likely leads us to disconnect the peer). RFC 6093 doesn't forbid this, but the current approach seems more clear and direct to me.

A new unit test in sock_tests covers the fix itself: with an urgent byte pending, waiting for RecvEvent must not report ErrorEvent. Without the fix it fails on a select() build.

Backports until 29.x are straight-forward, but for 31.x and before require compensating for the scripted-diff in github.com/bitcoin/bitcoin@f395acdeee.

Alternative approach to #36688, citing the relevant parts of its description: > There is currently nothing preventing us to receive TCP urgent data, which would never be returned by `recv()`. Linux's `poll()` is indifferent to this, but the `select()` socket monitoring may keep reporting it as pending on some platforms. > > This would not prevent progress nor lead to a crash anymore after #36665, but it's still undesirable. Fix this by only adding a socket to the `select()` exception set while waiting for a non-blocking `connect()` to complete. Windows needs that to detect a failed connection. Established connections no longer monitor the exception set on any platform. This approach was suggested by theuni in https://github.com/bitcoin/bitcoin/pull/36716#issuecomment-6931290348. To opt in, `ErrorEvent` can now be requested from `Sock::Wait()`, like `RecvEvent` and `SendEvent`. With `select()` that adds the socket to the exception set. `ConnectToSocket()` is the only caller that requests it. There is no behavior change with `poll()`, which reports errors whether or not they are requested. Using `ErrorEvent` for this was suggested by vasild in https://github.com/bitcoin/bitcoin/pull/36716#discussion_r4692637894. We could instead have set `SO_OOBINLINE` on our sockets, so `recv()` returns any urgent data sent to us (and likely leads us to disconnect the peer). RFC 6093 doesn't forbid this, but the current approach seems more clear and direct to me. A new unit test in `sock_tests` covers the fix itself: with an urgent byte pending, waiting for `RecvEvent` must not report `ErrorEvent`. Without the fix it fails on a `select()` build. Backports until 29.x are straight-forward, but for 31.x and before require compensating for the scripted-diff in https://github.com/bitcoin/bitcoin/commit/f395acdeeeaa1f3fd75d3cedbf2731fa24083e9f.
DrahtBot commented 2026-10-31 04:13:59 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK theuni, darosior, vasild
Concept ACK midnightmagic

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36916 (test: avoid BSD ephemeral-port collisions in HTTP clients by willcl-ark)
  • #36147 (ci: add native freeBSD ci job by willcl-ark)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/test/sock_tests.cpp: sender.Send("x", 1, 0)

2026-11-25 16:42:31

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36716 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36716.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36716#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [theuni](https://github.com/bitcoin/bitcoin/pull/36716#pullrequestreview-6061583481), [darosior](https://github.com/bitcoin/bitcoin/pull/36716#pullrequestreview-6061703423), [vasild](https://github.com/bitcoin/bitcoin/pull/36716#pullrequestreview-6075156735) | | Concept ACK | [midnightmagic](https://github.com/bitcoin/bitcoin/pull/36716#issuecomment-6673573479) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36916](https://github.com/bitcoin/bitcoin/pull/36916) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36916.svg"></sub> (test: avoid BSD ephemeral-port collisions in HTTP clients by willcl-ark) * [#36147](https://github.com/bitcoin/bitcoin/pull/36147) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36147.svg"></sub> (ci: add native freeBSD ci job by willcl-ark) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### LLM Linter (✨ experimental) Possible places where named args for integral literals may be used (e.g. `func(x, /*named_arg=*/0)` in C++, and `func(x, named_arg=0)` in Python): - `src/test/sock_tests.cpp`: `sender.Send("x", 1, 0)` <sup>2026-11-25 16:42:31</sup>
Sjors commented 2026-10-31 04:14:23 +00:00 (Migrated from github.com)

(I'll update the PR description later, for now see discussion in #35918 36688)

(I'll update the PR description later, for now see discussion in #35918 36688)
First-time contributor

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.

🔵 Suggestion · Failed-connect tests do not guard the explicit ErrorEvent request

The current code preserves Windows connect-failure detection, but the tests do not directly guard against dropping ErrorEvent and making refused non-blocking connects wait until timeout.

Location: src/netbase.cpp:606 (head).

Review coverage was incomplete.


Reviewed: 97e3c9562291 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:5ba05739881855cba25c3c05d6f82a61b8a0665f --> <!-- ralph-head:97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6 --> <!-- ralph-case:20b803a3473aa27fb25ca8432d403258b920bbdd603f57b019e946e14fecbd34 --> Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · Failed-connect tests do not guard the explicit `ErrorEvent` request** The current code preserves Windows connect-failure detection, but the tests do not directly guard against dropping `ErrorEvent` and making refused non-blocking connects wait until timeout. Location: [`src/netbase.cpp:606`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6/src/netbase.cpp#L606>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`97e3c9562291`](<https://git.fish.foo/bitcoin/bitcoin/commit/97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6>) · [Review report](<https://review.fish.foo/report/36716-97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6-3128-9.html>) · [Previous reports](<https://review.fish.foo/traces/36716/>) [permalink](<https://review.fish.foo/report/36716-97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6-3128-9.html>)
pinheadmz commented 2026-10-31 11:38:09 +00:00 (Migrated from github.com)

Mine as well apply the same logic to HTTP, probably right here:

github.com/bitcoin/bitcoin@5669fda5ed/src/httpserver.cpp (L916-L918)

I wrote functional test for the first PR, could be adapted to ensuring HTTP disconnects on urgent data:

https://gist.github.com/pinheadmz/f5bb77865f870865e44c54d5751b569a

Mine as well apply the same logic to HTTP, probably right here: https://github.com/bitcoin/bitcoin/blob/5669fda5ed85ac739c1678c03bd7c25193d099c6/src/httpserver.cpp#L916-L918 I wrote functional test for the first PR, could be adapted to ensuring HTTP disconnects on urgent data: https://gist.github.com/pinheadmz/f5bb77865f870865e44c54d5751b569a
Sjors commented 2026-11-01 07:42:57 +00:00 (Migrated from github.com)

My preference is to fix HTTP separately as a followup, but I'm open to doing it here.

My preference is to fix HTTP separately as a followup, but I'm open to doing it here.
vasild (Migrated from github.com) reviewed 2026-11-02 16:09:50 +00:00
Lines 2205-2206
vasild (Migrated from github.com) commented 2026-11-02 16:09:42 +00:00

Should the below if (recvSet || errorSet) be revised as well? If we only set errorSet on Windows and we already handle it here, then the below can be just if (recvSet).

Or, given that we only set errorSet on Windows, this #ifdef WIN32 here is not needed.

Should the below `if (recvSet || errorSet)` be revised as well? If we only set `errorSet` on Windows and we already handle it here, then the below can be just `if (recvSet)`. Or, given that we only set `errorSet` on Windows, this `#ifdef WIN32` here is not needed.
Lines 222-225
vasild (Migrated from github.com) commented 2026-11-02 16:05:19 +00:00

Some lines below is this code:

         if (FD_ISSET(s, &err)) {
             events.occurred |= ErrorEvent;
         }       

which handles the outcome of select(2). Is it true that with this PR that would be no-op on non-Windows? Because we only FD_SET(s, &err) on Windows. If yes, then consider also putting it inside #ifdef WIN32 to make that more clear.

Some lines below is this code: ```cpp if (FD_ISSET(s, &err)) { events.occurred |= ErrorEvent; } ``` which handles the outcome of `select(2)`. Is it true that with this PR that would be no-op on non-Windows? Because we only `FD_SET(s, &err)` on Windows. If yes, then consider also putting it inside `#ifdef WIN32` to make that more clear.
darosior (Migrated from github.com) reviewed 2026-11-02 23:55:51 +00:00
darosior (Migrated from github.com) left a comment

crACK 1fde57f1de because it fixes the issue in P2P, but i prefer @theuni's suggestion to just always fail on error/exception during a wait (And i guess start listening for POLLPRI on Linux to consistently disconnect on URG data rather than ignoring it on one platform and disconnecting on another).

I don't understand the point of the second commit.

crACK 1fde57f1deda683129ccead9c30cfad0e235914e because it fixes the issue in P2P, but i prefer @theuni's [suggestion](https://github.com/bitcoin/bitcoin/pull/36688#issuecomment-6528271842) to just always fail on error/exception during a wait (And i guess start listening for POLLPRI on Linux to consistently disconnect on URG data rather than ignoring it on one platform and disconnecting on another). I don't understand the point of the second commit.
darosior (Migrated from github.com) commented 2026-11-02 23:55:16 +00:00

This does not follow, and regardless that seems like a confusing comment to add here.

My reading of RFC 6093 is that it 1) discourages applications from sending urgent data 2) advises applications to set SO_OOBINLINE to fix the broken out of band mechanism regardless of their use for urgent data.

But regardless, i think that comment just adds more confusion than it clears up, and it would be better to drop it.

This does not follow, and regardless that seems like a confusing comment to add here. My reading of RFC 6093 is that it 1) discourages applications from sending urgent data 2) advises applications to set SO_OOBINLINE to fix the broken out of band mechanism regardless of their use for urgent data. But regardless, i think that comment just adds more confusion than it clears up, and it would be better to drop it.
Sjors (Migrated from github.com) reviewed 2026-11-04 08:23:22 +00:00
Sjors (Migrated from github.com) commented 2026-11-04 08:23:22 +00:00
  1. discourages applications from sending urgent data

The RFC says:

Even though applications SHOULD NOT employ the urgent mechanism

This isn't about a misbehaving sender, but rather about application design (both sides).

This does not follow

I'm not sure what exactly "this" refers to. It's true that the RFC does not forbid applications from setting SO_OOBINLINE if they don't "employ urgent indications".

I do think it's good to document that we don't "employ urgent indications". The absence of the setting implies it, but an actual code comment is more clear.

In any case, I'll drop the comment commit.

> 1) discourages applications from sending urgent data The RFC says: > Even though applications SHOULD NOT employ the urgent mechanism This isn't about a misbehaving sender, but rather about application design (both sides). > This does not follow I'm not sure what exactly "this" refers to. It's true that the RFC does not forbid applications from setting `SO_OOBINLINE` if they don't "employ urgent indications". I do think it's good to document that we don't "employ urgent indications". The absence of the setting implies it, but an actual code comment is more clear. In any case, I'll drop the comment commit.
Sjors (Migrated from github.com) reviewed 2026-11-04 11:44:08 +00:00
Lines 222-225
Sjors (Migrated from github.com) commented 2026-11-04 11:44:08 +00:00

Added a commit for this.

Added a commit for this.
Sjors (Migrated from github.com) reviewed 2026-11-04 13:53:03 +00:00
Lines 2205-2206
Sjors (Migrated from github.com) commented 2026-11-04 13:53:03 +00:00

Should the below if (recvSet || errorSet) be revised as well?

I added a commit to check errorSet separately and earlier, for poll().

I spent some time trying to understand if that's a behavior change, but AFAIK it just emits a different log message. I added a test to demonstrate that.

> Should the below `if (recvSet || errorSet)` be revised as well? I added a commit to check `errorSet` separately and earlier, for `poll()`. I spent some time trying to understand if that's a behavior change, but AFAIK it just emits a different log message. I added a test to demonstrate that.
Sjors commented 2026-11-04 15:57:20 +00:00 (Migrated from github.com)

I dropped the comment-only commit.

Added two commits based on @vasild's feedback.

Also added and expanded @pinheadmz's tests.

Finally, I added the http fix at the end. It should be simple to review since it's the same approach.

I also tested on Windows native.

I dropped the comment-only commit. Added two commits based on @vasild's feedback. Also added and expanded @pinheadmz's tests. Finally, I added the http fix at the end. It should be simple to review since it's the same approach. I also tested on Windows native.
midnightmagic commented 2026-11-06 00:48:53 +00:00 (Migrated from github.com)

We could instead have set SO_OOBINLINE on our sockets, so recv() returns any urgent data sent to us (and likely leads us to disconnect the peer). RFC 6093 doesn't forbid this, but the current approach seems more clear and direct to me.

I believe it's possible to construct an oob urgent ptr for data which will never be sent and which will then never be received but will still trigger the exception set. Setting SO_OOBINLINE thus can't ultimately clear the select() exception because no data is actually inline to read. On the BSDs I examined (and therefore likely OS/X) this will still generate an exception so the current select() call will return immediately again. As noted elsewhere, this doesn't technically prevent eventual node progress.

fwiw, I strongly suggest that oob data be considered an error condition based on this. There is nowhere for UNIX-y OSes which an oob byte will ever be generated by a valid p2p peer, and thus it'll only ever be generated in this context — therefore disconnection is a logical and completely fair result. I personally think at this point it's worth a ban.

(Uh, just to be clear, at the very least I think we should delete the exceptfds from the select() call entirely, so strong ACK for this approach.)

> We could instead have set `SO_OOBINLINE` on our sockets, so `recv()` returns any urgent data sent to us (and likely leads us to disconnect the peer). RFC 6093 doesn't forbid this, but the current approach seems more clear and direct to me. I believe it's possible to construct an oob urgent ptr for data which will never be sent and which will then never be received but will still trigger the exception set. Setting SO_OOBINLINE thus can't ultimately clear the select() exception because no data is actually inline to read. On the BSDs I examined (and therefore likely OS/X) this will still generate an exception so the current select() call will return immediately again. As noted elsewhere, this doesn't technically prevent eventual node progress. fwiw, I strongly suggest that oob data be considered an error condition based on this. There is nowhere for UNIX-y OSes which an oob byte will ever be generated by a valid p2p peer, and thus it'll only ever be generated in this context — therefore disconnection is a logical and completely fair result. I personally think at this point it's worth a ban. (Uh, just to be clear, at the very least I think we should delete the exceptfds from the select() call entirely, so strong ACK for this approach.)
Sjors commented 2026-11-06 08:43:34 +00:00 (Migrated from github.com)

I strongly suggest that oob data be considered an error condition based on this

I agree that if there was a DISCONNECT_ON_OOB flag, we should set it. But we can't directly detect if such data was present. All we can know is that errorSet was triggered, which could be for unrelated OS reasons. That could cause us to disconnect a well behaved peer.

That's why this PR simply ignores the exception set (outside Windows), instead of trying to handle it. It might be possible with poll(), but that would be better for a followup.

> I strongly suggest that oob data be considered an error condition based on this I agree that if there was a `DISCONNECT_ON_OOB` flag, we should set it. But we can't directly detect if such data was present. All we can know is that `errorSet` was triggered, which could be for unrelated OS reasons. That could cause us to disconnect a well behaved peer. That's why this PR simply ignores the exception set (outside Windows), instead of trying to handle it. It might be possible with poll(), but that would be better for a followup.
theuni commented 2026-11-06 21:27:55 +00:00 (Migrated from github.com)

@midnightmagic agreed.

Imo we should just always disconnect when an exception is set, or when oob/prio are found. I don't see any need for platform-specific behavior here. I'd rather go with: https://github.com/theuni/bitcoin/commits/net-oob-error/

That branch unifies the select/poll behaviors, and causes a disconnect (on all platforms) if any of those conditions are true.

It differs from what's here in that it turns POLLHUP into a read event as it should be, rather than an error. That simplifies things significantly, as it allows draining to happen naturally, and it means that the exception set is truly only comprised of exceptions.

If receiving is off (meaning that we have data to send) and we receive a SIGHUP, we'll disconnect on the next send.

It fixes up the tests to show that OOB data always causes a disconnect.

@midnightmagic agreed. Imo we should just always disconnect when an exception is set, or when oob/prio are found. I don't see any need for platform-specific behavior here. I'd rather go with: https://github.com/theuni/bitcoin/commits/net-oob-error/ That branch unifies the select/poll behaviors, and causes a disconnect (on all platforms) if any of those conditions are true. It differs from what's here in that it turns `POLLHUP` into a read event as it should be, rather than an error. That simplifies things significantly, as it allows draining to happen naturally, and it means that the exception set is truly only comprised of exceptions. If receiving is off (meaning that we have data to send) and we receive a SIGHUP, we'll disconnect on the next send. It fixes up the tests to show that OOB data always causes a disconnect.
DrahtBot commented 2026-11-07 13:55:37 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-11-09 12:07:18 +00:00 (Migrated from github.com)

Rebased after #36744.

@theuni wrote:

Imo we should just always disconnect when an exception is set

So you're not worried about the operating system triggering this set for reasons that have nothing to do with OOB data?

That branch unifies the select/poll behaviors, and causes a disconnect (on all platforms) if any of those conditions are true.

Since that's a completely different approach from this PR, it seems better to open it as a separate (and alternative) PR.

Rebased after #36744. @theuni wrote: > Imo we should just always disconnect when an exception is set So you're not worried about the operating system triggering this set for reasons that have nothing to do with OOB data? > That branch unifies the select/poll behaviors, and causes a disconnect (on all platforms) if any of those conditions are true. Since that's a completely different approach from this PR, it seems better to open it as a separate (and alternative) PR.
theuni commented 2026-11-16 18:15:42 +00:00 (Migrated from github.com)

Ok, I retract the above. After experimenting for the last few days, nothing really works here to align the two behaviors without logical hacks.

I really dislike the platform-specific hacks here, but I agree that they're a necessary evil as long as we're supporting select and poll. I'll drop the suggestion to use my branch and review what's here for correctness.

Ok, I retract the above. After experimenting for the last few days, nothing really works here to align the two behaviors without logical hacks. I really dislike the platform-specific hacks here, but I agree that they're a necessary evil as long as we're supporting `select` and `poll`. I'll drop the suggestion to use my branch and review what's here for correctness.
theuni commented 2026-11-16 22:28:19 +00:00 (Migrated from github.com)

Sorry to throw yet another wrench in this, but when trying to tease apart the uses and platform differences for the select error set, it occurred to me that all of the hacks have to do with the fact that we have a single obscure use-case for that set, and in all other cases it's harmful. Rather than trying to isolate the platforms that require that use-case, why not isolate the use-case instead?

Please see here: github.com/theuni/bitcoin@f8fbc168bb for a change that splits out the connection failure case. That allows us to completely ignore the select error set in all other cases where it'd be considered harmful. Imo that's much cleaner because it requires a single opt-in where needed, rather than opt-outs sprinkled all around.

With that change, I don't think the early if (errorSet && !recvSet) disconnects are needed at all, but could (and probably should) be added for belt-and-suspenders.

@Sjors @darosior mind taking a look?

Sorry to throw yet another wrench in this, but when trying to tease apart the uses and platform differences for the select error set, it occurred to me that all of the hacks have to do with the fact that we have a single obscure use-case for that set, and in all other cases it's harmful. Rather than trying to isolate the platforms that require that use-case, why not isolate the use-case instead? Please see here: https://github.com/theuni/bitcoin/commit/f8fbc168bbe0995d498a1ee594515869a78d4361 for a change that splits out the connection failure case. That allows us to completely ignore the select error set in all other cases where it'd be considered harmful. Imo that's much cleaner because it requires a single opt-in where needed, rather than opt-outs sprinkled all around. With that change, I don't think the early `if (errorSet && !recvSet)` disconnects are needed at all, but could (and probably should) be added for belt-and-suspenders. @Sjors @darosior mind taking a look?
Sjors commented 2026-11-18 17:36:51 +00:00 (Migrated from github.com)

@theuni to put it into my own words, IIUC:

There's two phases to a connection, phase 1 establishes it ConnectToSocket and phase 2 maintains it after (in GenerateWaitSockets, etc). Your proposal makes it so that in phase 2 nothing watches errorSet, while in phase 1 it's now watched on all platforms. A follow-up could narrow phase 1 to just Windows as belt-and-suspenders.

This makes sense, and I adopted it.

On ancient versions of Windows it was unsafe to ignore errorSet, and it had to be drained to prevent memory exhaustion. See https://mailarchive.ietf.org/arch/msg/tcpm/55ecR94wP1NkrL5cuPj0PWtTIXc/

The following checks for this: https://gist.github.com/Sjors/9582259267a038e06c7f0730356416de

I tested on a physical Windows 11 Home 26H2 machine. Connections reset after 17 urgent bytes. I also tested Windows Server 2022 on a Github CI runner: https://github.com/Sjors/bitcoin/actions/runs/44390882699/job/135107875034

The latter should roughly match Windows 10 in this regard, which is the oldest version we support. So this is no longer a concern in theory, but it doesn't hurt to actually try if you can find such a machine.

BSD is probably also worth testing, cc @vasild.

@theuni to put it into my own words, IIUC: There's two phases to a connection, phase 1 establishes it `ConnectToSocket` and phase 2 maintains it after (in `GenerateWaitSockets`, etc). Your proposal makes it so that in phase 2 nothing watches `errorSet`, while in phase 1 it's now watched on all platforms. A follow-up could narrow phase 1 to just Windows as belt-and-suspenders. This makes sense, and I adopted it. On ancient versions of Windows it was unsafe to ignore `errorSet`, and it had to be drained to prevent memory exhaustion. See https://mailarchive.ietf.org/arch/msg/tcpm/55ecR94wP1NkrL5cuPj0PWtTIXc/ The following checks for this: https://gist.github.com/Sjors/9582259267a038e06c7f0730356416de I tested on a physical Windows 11 Home 26H2 machine. Connections reset after 17 urgent bytes. I also tested Windows Server 2022 on a Github CI runner: https://github.com/Sjors/bitcoin/actions/runs/44390882699/job/135107875034 The latter should roughly match Windows 10 in this regard, which is the oldest version we support. So this is no longer a concern in theory, but it doesn't hurt to actually try if you can find such a machine. BSD is probably also worth testing, cc @vasild.
theuni (Migrated from github.com) reviewed 2026-11-18 22:59:44 +00:00
theuni (Migrated from github.com) left a comment

Approach ACK, thanks for the update.

See my comment about keeping the (recvSet || errorSet) check as-is.

Other than that, looks good to me.

Approach ACK, thanks for the update. See my comment about keeping the `(recvSet || errorSet)` check as-is. Other than that, looks good to me.
theuni (Migrated from github.com) commented 2026-11-18 22:57:47 +00:00

According to the poll Linux manpage, we may receive a lone POLLHUP (without POLLIN or POLLERR) when the socket has been drained and the next recv would close it. I think if we skip the || errorSet here, we could end up waking for the error (POLLHUP) event, and never doing anything with it. Then we're back to the tight loop.

Since select is a no-op here now, I don't see the harm in leaving this as if (recvSet || errorSet) ?

Here's the output of the Linux manpage example. It's a file descriptor rather than a socket, it's possible that the behavior is different.

 $ ./poll myfifo
Opened "myfifo" on fd 3
About to poll()
Ready: 1
  fd=3; events: POLLIN POLLHUP
    read 4 bytes: foo

About to poll()
Ready: 1
  fd=3; events: POLLHUP
    closing fd 3
All file descriptors closed; bye
According to the `poll` Linux manpage, we may receive a lone `POLLHUP` (without `POLLIN` or `POLLERR`) when the socket has been drained and the next recv would close it. I think if we skip the `|| errorSet` here, we could end up waking for the error (`POLLHUP`) event, and never doing anything with it. Then we're back to the tight loop. Since `select` is a no-op here now, I don't see the harm in leaving this as `if (recvSet || errorSet)` ? Here's the output of the Linux manpage example. It's a file descriptor rather than a socket, it's possible that the behavior is different. ```bash $ ./poll myfifo Opened "myfifo" on fd 3 About to poll() Ready: 1 fd=3; events: POLLIN POLLHUP read 4 bytes: foo About to poll() Ready: 1 fd=3; events: POLLHUP closing fd 3 All file descriptors closed; bye ```
theuni (Migrated from github.com) commented 2026-11-18 22:36:46 +00:00

I experimented with removing select() entirely on top of this changeset, and ended up needing a little change here. Rather than recvSet, what we really want to test (as your comment states) is recvReq, where

bool recvReq = it->second.requested & Sock::RecvEvent;

I don't think it matters here, but in order to support poll in a cross-platform way, the exact condition we want to test is "did we see an error when we didn't request a receive event", which is slightly different than "did we see an error when we didn't SEE a receive event" as we have here.

This matters for platforms (Windows) which raise only POLLERR | POLLHUP for disconnections, even when POLLIN was requested.

Again.. it shouldn't matter here. Just pointing it out for the future.

I experimented with removing `select()` entirely on top of this changeset, and ended up needing a little change here. Rather than `recvSet`, what we really want to test (as your comment states) is `recvReq`, where ```c++ bool recvReq = it->second.requested & Sock::RecvEvent; ``` I don't think it matters here, but in order to support poll in a cross-platform way, the exact condition we want to test is "did we see an error when we didn't request a receive event", which is slightly different than "did we see an error when we didn't SEE a receive event" as we have here. This matters for platforms (Windows) which raise only `POLLERR | POLLHUP` for disconnections, even when `POLLIN` was requested. Again.. it shouldn't matter here. Just pointing it out for the future.
Sjors (Migrated from github.com) reviewed 2026-11-19 10:00:07 +00:00
Sjors (Migrated from github.com) commented 2026-11-19 10:00:07 +00:00

The concept of recvRequested makes a lot of sense, so I added this and used it for the early disconnect.

67bdc2d3b5 -> 8b8a2f4926

Also applied to http in 05084e7879.

The concept of `recvRequested` makes a lot of sense, so I added this and used it for the early disconnect. 67bdc2d3b5c62dd4d8cf0eb757b78fcf0d5b56b3 -> 8b8a2f49267daa6a3f9d85d9cb511bd7c286e52a Also applied to http in 05084e7879140aaf7c9b77e372ebc828f98e3153.
Sjors (Migrated from github.com) reviewed 2026-11-19 10:00:09 +00:00
Sjors (Migrated from github.com) commented 2026-11-19 10:00:09 +00:00

I think if we skip the || errorSet here

The poll code in WaitMany sets errorSet if it gets POLLHUP. The if (errorSet && !recvSet) check above disconnects, so we don't get here.

I still dropped this change: 67bdc2d3b5 -> 8b8a2f4926

Given that SocketHandlerConnected() only handles established connections:

  • with select(), errorSet is never set, so recvSet || errorSet is just recvSet
  • with poll(), a lone POLLHUP or POLLERR gives errorSet && !recvSet, which the early disconnect above already handles
> I think if we skip the `|| errorSet` here The poll code in `WaitMany` sets `errorSet` if it gets POLLHUP. The `if (errorSet && !recvSet)` check above disconnects, so we don't get here. I still dropped this change: 67bdc2d3b5c62dd4d8cf0eb757b78fcf0d5b56b3 -> 8b8a2f49267daa6a3f9d85d9cb511bd7c286e52a Given that `SocketHandlerConnected()` only handles established connections: - with `select()`, `errorSet` is never set, so `recvSet || errorSet` is just `recvSet` - with `poll()`, a lone `POLLHUP` or `POLLERR` gives `errorSet && !recvSet`, which the early disconnect above already handles
darosior (Migrated from github.com) reviewed 2026-11-19 19:46:31 +00:00
darosior (Migrated from github.com) commented 2026-11-19 18:43:21 +00:00

Why the jump from (1 << 2) to (1 << 4)?

Why the jump from (1 << 2) to (1 << 4)?
darosior (Migrated from github.com) reviewed 2026-11-19 22:18:31 +00:00
darosior (Migrated from github.com) left a comment

This PR has changed multiple times, and considerably grown, since it was opened. And it's also losing momentum, now failing CI, whereas it's currently the main PR for an important fix. So i think it's worth taking a step back and asking what it's trying to achieve.

I think the initial goal was to get a minimal fix in, because a proper cleanup of this logic like #36761 would be riskier to backport. But now this PR adds as much code as switching to poll entirely (and removes 10 times less).

It's not exactly trivial code either: we introduce new flags to Sock, leak the connection stage down to the socket wait logic to only register the exception set at this point, have some callers (but not all!) now disconnect on errors.. That's a bunch of behaviour changes not strictly necessary to fix the bug, that i would be hesitant to backport (i.e. ship with much less testing --especially if we deem the bug important enough to cut minor releases as soon as the fix is ready).

On top of that, this PR adds a whole bunch of functional tests that seem pretty brittle to me, since they rely on kernel settings that may differ between machines, or break when we update CI (that's the reason why i did not push similar tests i had performed locally to #36688). It's also not clear to me how useful they are, as they wouldn't even catch the bug this PR set out to fix in the first place (following my review comment below i tested this by cherry-picking your tests on master and running them on a Windows VM).

Why not go back to the simple approach of simply always disconnecting when a wait returns an ErrorEvent? It's short, easy to reason about and safer to backport.

Sure, it preserves the behaviour difference between platforms using select() and those using poll(). That can be cleaned up later, in a more involved change we don't intend to backport, since this is a pre-existing issue.

This PR has changed multiple times, and considerably grown, since it was opened. And it's also losing momentum, now failing CI, whereas it's currently the main PR for an important fix. So i think it's worth taking a step back and asking what it's trying to achieve. I think the initial goal was to get a minimal fix in, because a proper cleanup of this logic like #36761 would be riskier to backport. But now this PR adds as much code as [switching to poll entirely](https://github.com/darosior/bitcoin/compare/2610_ditch_select~6..2610_ditch_select) (and removes 10 times less). It's not exactly trivial code either: we introduce new flags to Sock, leak the connection stage down to the socket wait logic to only register the exception set at this point, have some callers (but not all!) now disconnect on errors.. That's a bunch of behaviour changes not strictly necessary to fix the bug, that i would be hesitant to backport (i.e. ship with much less testing --especially if we deem the bug important enough to cut minor releases as soon as the fix is ready). On top of that, this PR adds a whole bunch of functional tests that seem pretty brittle to me, since they rely on kernel settings that may differ between machines, or break when we update CI (that's the reason why i did not push similar tests i had performed locally to #36688). It's also not clear to me how useful they are, as they wouldn't even catch the bug this PR set out to fix in the first place (following my review comment below i tested this by cherry-picking your tests on master and running them on a Windows VM). Why not go back to the simple approach of simply always disconnecting when a wait returns an `ErrorEvent`? It's short, easy to reason about and safer to backport. Sure, it preserves the behaviour difference between platforms using select() and those using poll(). That can be cleaned up later, in a more involved change we don't intend to backport, since this is a pre-existing issue.
darosior (Migrated from github.com) commented 2026-11-19 22:10:15 +00:00

Yes, it demonstrates progress. But the bug you are trying to fix in this PR is not a lack of progress on urgent data.

Yes, it demonstrates progress. But the bug you are trying to fix in this PR is not a lack of progress on urgent data.
theuni (Migrated from github.com) reviewed 2026-11-19 22:18:39 +00:00
theuni (Migrated from github.com) commented 2026-11-19 22:18:39 +00:00

Just keeping the low half reserved for Events and the high for Flags. I can't imagine it matters in any real way... 1 << 3 is fine if you prefer it.

After all, this is just a hack to keep the diff small as opposed to adding the more straightforward WaitForNewConnection() function.

Just keeping the low half reserved for Events and the high for Flags. I can't imagine it matters in any real way... `1 << 3` is fine if you prefer it. After all, this is just a hack to keep the diff small as opposed to adding the more straightforward `WaitForNewConnection()` function.
midnightmagic commented 2026-11-20 00:23:07 +00:00 (Migrated from github.com)

I strongly suggest that oob data be considered an error condition based on this

I agree that if there was a DISCONNECT_ON_OOB flag, we should set it. But we can't directly detect if such data was present. All we can know is that errorSet was triggered, which could be for unrelated OS reasons. That could cause us to disconnect a well behaved peer.

That's why this PR simply ignores the exception set (outside Windows), instead of trying to handle it. It might be possible with poll(), but that would be better for a followup.

Minor context: On many OSes (mostly BSD-derived) I believe there is only a single trigger for the exceptfd set in a select() call for a normal TCP socket and that's OOB data. The reason to consider OOB data now almost certainly hostile incoming data in all cases is because the codebase's current (?) behaviour makes it so the only reasonable interpretation is a hostile action — i.e. there is no well-behaving peer which will ever generate OOB data and send it to us.

If the codebase ignores it in a way where someone sending it means nothing — yes absolutely that will solve the problem in the least and most minimally-invasive fashion, and people like myself will just run our own detection patch independently. I agree with you in that if we're immune to it in the first place, detecting it above that is just special-case pointlessness. My only concern really is making sure the .. uh error condition isn't possible anymore. So, yeah you're right.

Elsewise if we retain the ability to detect OOB data, a noisy log entry and a disconnect would be welcome to folks like myself but certainly not necessary. I really don't have a particular dog in this race either way, and I'll just be grateful when the error condition gets fixed.

> > I strongly suggest that oob data be considered an error condition based on this > > I agree that if there was a `DISCONNECT_ON_OOB` flag, we should set it. But we can't directly detect if such data was present. All we can know is that `errorSet` was triggered, which could be for unrelated OS reasons. That could cause us to disconnect a well behaved peer. > > That's why this PR simply ignores the exception set (outside Windows), instead of trying to handle it. It might be possible with poll(), but that would be better for a followup. Minor context: On many OSes (mostly BSD-derived) I believe there is only a single trigger for the exceptfd set in a select() call for a normal TCP socket and that's OOB data. The reason to consider OOB data now almost certainly hostile incoming data in all cases is because the codebase's current (?) behaviour makes it so the only reasonable interpretation is a hostile action — i.e. there is no well-behaving peer which will ever generate OOB data and send it to us. If the codebase ignores it in a way where someone sending it means nothing — yes absolutely that will solve the problem in the least and most minimally-invasive fashion, and people like myself will just run our own detection patch independently. I agree with you in that if we're immune to it in the first place, detecting it above that is just special-case pointlessness. My only concern really is making sure the .. uh error condition isn't possible anymore. So, yeah you're right. Elsewise if we retain the ability to detect OOB data, a noisy log entry and a disconnect would be welcome to folks like myself but certainly not necessary. I really don't have a particular dog in this race either way, and I'll just be grateful when the error condition gets fixed.
Sjors commented 2026-11-23 13:28:12 +00:00 (Migrated from github.com)

@darosior would it make sense to merge this and backport your simpler version?

If you do want to go for a different approach, it's better if you or someone else (possibly me) opens a PR for that, rather than changing this PR back and forth.

The tests were added because reviewers suggested them. You're the first to push back on them. They help illustrate what this PR changes and what stays the same. For the master branch I think they're fine, and if they turn out difficult to maintain they can just be dropped.

especially if we deem the bug important enough to cut minor releases as soon as the fix is ready

I don't think it is based on my current understanding. I would rather see the backport properly tested, and then it can be shipped along with whatever more urgent backport fix comes next.

@darosior would it make sense to merge this and backport your simpler version? If you do want to go for a different approach, it's better if you or someone else (possibly me) opens a PR for that, rather than changing this PR back and forth. The tests were added because reviewers suggested them. You're the first to push back on them. They help illustrate what this PR changes and what stays the same. For the master branch I think they're fine, and if they turn out difficult to maintain they can just be dropped. > especially if we deem the bug important enough to cut minor releases as soon as the fix is ready I don't think it is based on my current understanding. I would rather see the backport properly tested, and then it can be shipped along with whatever more urgent backport fix comes next.
darosior commented 2026-11-23 15:27:33 +00:00 (Migrated from github.com)

I don't think it makes sense to backport something different than what gets merged on master. The vast majority of our testing comes from development, which happens on master. Release candidates barely receive any testing. Backporting something other than what gets merged in master boils down to releasing code that will only have been tested / ran by whomever looks at the backport PRs (which usually get less attention than regular PRs). At that point i'd rather we don't backport anything.

I didn't want to step on your toes, and figured it would be better that we concentrate attention on a single PR to fix this bug. But i also agree with changing this PR back and forth, and if you'd rather i open a different approach, and reviewers can judge which they prefer, i am happy to do that.

Why insist on committing to master tests that do not even catch the bug you are fixing, but still may introduce flakiness because they rely on low level kernel parameters which may change across time and machines? That just does not make any sense to me.

I agree it is not necessary to rush a minor release for this. Having it backported in the branch, ready to be released, would be good though: it means that we can make binaries available within a couple days if people are encountering the issue in the wild.

I don't think it makes sense to backport something different than what gets merged on master. The vast majority of our testing comes from development, which happens on master. Release candidates barely receive any testing. Backporting something other than what gets merged in master boils down to releasing code that will only have been tested / ran by whomever looks at the backport PRs (which usually get less attention than regular PRs). At that point i'd rather we don't backport anything. I didn't want to step on your toes, and figured it would be better that we concentrate attention on a single PR to fix this bug. But i also agree with changing this PR back and forth, and if you'd rather i open a different approach, and reviewers can judge which they prefer, i am happy to do that. Why insist on committing to master tests that do not even catch the bug you are fixing, but still may introduce flakiness because they rely on low level kernel parameters which may change across time and machines? That just does not make any sense to me. I agree it is not necessary to rush a minor release for this. Having it backported in the branch, ready to be released, would be good though: it means that we can make binaries available within a couple days if people are encountering the issue in the wild.
Sjors commented 2026-11-23 15:28:50 +00:00 (Migrated from github.com)

I plan to drop the http commit to make it easier to backport, given that 30.x and 31.x still use Libevent. I'll open a follow-up with that (if and) after this is merged.

On top of that, this PR adds a whole bunch of functional tests that seem pretty brittle to me

I tested backports down to 29.x, which indeed reveals problems. I'm going to try to make the test more robust, and otherwise drop it and instead add it to a gist that reviewers can use (like the windows stress test).

tests that do not even catch the bug you are fixing

You said it was brittle, not that it didn't work. Obviously I don't want to include tests that don't work.

I plan to drop the http commit to make it easier to backport, given that 30.x and 31.x still use Libevent. I'll open a follow-up with that (if and) after this is merged. > On top of that, this PR adds a whole bunch of functional tests that seem pretty brittle to me I tested backports down to 29.x, which indeed reveals problems. I'm going to try to make the test more robust, and otherwise drop it and instead add it to a gist that reviewers can use (like the windows stress test). > tests that do not even catch the bug you are fixing You said it was brittle, not that it didn't work. Obviously I don't want to include tests that don't work.
darosior commented 2026-11-23 16:18:40 +00:00 (Migrated from github.com)
Opened my suggested alternative as https://github.com/bitcoin/bitcoin/pull/36953.
theuni commented 2026-11-23 16:18:58 +00:00 (Migrated from github.com)

It's not exactly trivial code either: we introduce new flags to Sock, leak the connection stage down to the socket wait logic to only register the exception set at this point, have some callers (but not all!) now disconnect on errors.. That's a bunch of behaviour changes not strictly necessary to fix the bug, that i would be hesitant to backport (i.e. ship with much less testing --especially if we deem the bug important enough to cut minor releases as soon as the fix is ready).

I disagree with this framing. Yes, it was a winding road to get here, but the changes are straightforward:

  • Disconnect if we didn't request a read, but we get a hup/error event. This prevents us from reading when we shouldn't because we're paused. Afaik this would be safe to add by itself.
  • Registering for errors when using select is harmful in all but one case (detecting connection failures), and in that one it is required. Require callers to opt-in if they require this failure. For poll, this is a noop. This has the effect of disabling select "errors" that weren't really errors.

Otherwise, things stay the same. Draining for poll/select happens as before, but we avoid the harmful non-error "errors". We could add a few harmless #if[n]def USE_POLL in the higher layers to demonstrate where the changes have effects if that would help?

As I mentioned above, the less hackish way of doing this would be to introduce a WaitForNewConnection() which would be straightforward as the only way to register for an error event when using select. I proposed the more hackish event flag here instead to avoid having to change the Sock class and its derivatives, and the tests/fuzzers to go with it. I don't think we can have it all here.. either a quick hack that is small and targeted and backportable, or a more correct fix that's more invasive.

On top of that, this PR adds a whole bunch of functional tests that seem pretty brittle to me, since they rely on kernel settings that may differ between machines, or break when we update CI (that's the reason why i did not push similar tests i had performed locally to #36688). It's also not clear to me how useful they are, as they wouldn't even catch the bug this PR set out to fix in the first place (following my review comment below i tested this by cherry-picking your tests on master and running them on a Windows VM).

I'll admit I don't love the tests for this either. I'm not sure what to add here.

Why not go back to the simple approach of simply always disconnecting when a wait returns an ErrorEvent? It's short, easy to reason about and safer to backport.

IIRC my tests showed this was a behavioral change on Linux as we no longer do any socket draining once that error is received. We've had some discussions offline about the importance of that... I'm willing to concede that it might not matter in the end, but I'd be nervous to just assume it's fine and backport it. So to me, that's actually harder to reason about.

> It's not exactly trivial code either: we introduce new flags to Sock, leak the connection stage down to the socket wait logic to only register the exception set at this point, have some callers (but not all!) now disconnect on errors.. That's a bunch of behaviour changes not strictly necessary to fix the bug, that i would be hesitant to backport (i.e. ship with much less testing --especially if we deem the bug important enough to cut minor releases as soon as the fix is ready). I disagree with this framing. Yes, it was a winding road to get here, but the changes are straightforward: - Disconnect if we didn't request a read, but we get a hup/error event. This prevents us from reading when we shouldn't because we're paused. Afaik this would be safe to add by itself. - Registering for errors when using `select` is harmful in all but one case (detecting connection failures), and in that one it is required. Require callers to opt-in if they require this failure. For `poll`, this is a noop. This has the effect of disabling select "errors" that weren't really errors. Otherwise, things stay the same. Draining for `poll`/`select` happens as before, but we avoid the harmful non-error "errors". We could add a few harmless `#if[n]def USE_POLL` in the higher layers to demonstrate where the changes have effects if that would help? As I mentioned above, the less hackish way of doing this would be to introduce a `WaitForNewConnection()` which would be straightforward as the only way to register for an error event when using `select`. I proposed the more hackish event flag here instead to avoid having to change the `Sock` class and its derivatives, and the tests/fuzzers to go with it. I don't think we can have it all here.. either a quick hack that is small and targeted and backportable, or a more correct fix that's more invasive. > > On top of that, this PR adds a whole bunch of functional tests that seem pretty brittle to me, since they rely on kernel settings that may differ between machines, or break when we update CI (that's the reason why i did not push similar tests i had performed locally to #36688). It's also not clear to me how useful they are, as they wouldn't even catch the bug this PR set out to fix in the first place (following my review comment below i tested this by cherry-picking your tests on master and running them on a Windows VM). > I'll admit I don't love the tests for this either. I'm not sure what to add here. > Why not go back to the simple approach of simply always disconnecting when a wait returns an `ErrorEvent`? It's short, easy to reason about and safer to backport. > IIRC my tests showed this was a behavioral change on Linux as we no longer do any socket draining once that error is received. We've had some discussions offline about the importance of that... I'm willing to concede that it might not matter in the end, but I'd be nervous to just assume it's fine and backport it. So to me, that's actually harder to reason about.
darosior commented 2026-11-23 16:33:51 +00:00 (Migrated from github.com)

@theuni i agree with your concern but there is no behaviour change on Linux for a clean connection close. My approach leads to an earlier disconnect only in case a connection is reset. I'm investigating now how "normal" such connection resets are, and whether we do actually handle them properly today.

@theuni i agree with your concern but there is no behaviour change on Linux for a clean connection close. My approach leads to an earlier disconnect only in case a connection is reset. I'm investigating now how "normal" such connection resets are, and whether we do actually handle them properly today.
Sjors commented 2026-11-23 17:41:40 +00:00 (Migrated from github.com)

I dropped check_urgent_pointer_ahead from p2p_socket_errors.py, added a unit test, and moved the HTTP change to a follow-up.

The tests now do one of two things:

  • the unit test catches the bug: it fails without the fix on select() platforms
  • the functional test pins behavior (other than the log message change): that a single urgent byte is ignored, and that a reset while sending disconnects the peer without reading more input

(I was confused above about the distinction between tests being broken vs. not covering the fix itself)

See https://github.com/Sjors/bitcoin/actions/runs/45217725537/job/137861056516 for how the new unit tests fails on Windows without the fix. And https://github.com/Sjors/bitcoin/actions/runs/45217725537/job/137861056296 with the fix.

I checked that everything can be backported down to 29.x (with minor conflicts, see below).

The http commit is dropped for easier backport. For the same reason 9a61d7f17a is deferred for the followup PR.

Backports are easy, but for 31.x and before require compensating for the scripted-diff in f395acdeee, for the log format change in 22335474d7. If we also want to backport to 29.x then the scripted diff for fa9cf38ab6 and the infamous 9f36962b07 need to adjusted for.

I dropped `check_urgent_pointer_ahead` from `p2p_socket_errors.py`, added a unit test, and moved the HTTP change to a follow-up. The tests now do one of two things: - the unit test catches the bug: it fails without the fix on `select()` platforms - the functional test pins behavior (other than the log message change): that a single urgent byte is ignored, and that a reset while sending disconnects the peer without reading more input (I was confused above about the distinction between tests being broken vs. not covering the fix itself) See https://github.com/Sjors/bitcoin/actions/runs/45217725537/job/137861056516 for how the new unit tests fails on Windows without the fix. And https://github.com/Sjors/bitcoin/actions/runs/45217725537/job/137861056296 with the fix. I checked that everything can be backported down to 29.x (with minor conflicts, see below). The http commit is dropped for easier backport. For the same reason 9a61d7f17a is deferred for the followup PR. Backports are easy, but for 31.x and before require compensating for the scripted-diff in f395acdeeeaa1f3fd75d3cedbf2731fa24083e9f, for the log format change in 22335474d7. If we also want to backport to 29.x then the scripted diff for fa9cf38ab6 and the infamous 9f36962b07 need to adjusted for.
Sjors (Migrated from github.com) reviewed 2026-11-23 17:55:57 +00:00
Sjors (Migrated from github.com) commented 2026-11-23 17:55:57 +00:00

Adjusted the comment.

Adjusted the comment.
darosior commented 2026-11-23 18:50:01 +00:00 (Migrated from github.com)

Disconnect if we didn't request a read, but we get a hup/error event. This prevents us from reading when we shouldn't because we're paused. Afaik this would be safe to add by itself.

That seems fine to do as part of a larger cleanup, but as far as i know this is unrelated to the bug fix from this PR?

Registering for errors when using select is harmful in all but one case (detecting connection failures), and in that one it is required.

That makes sense to me. I agree with that approach conceptually, even if i dislike the specific implementation in this PR.

As I mentioned above, the less hackish way of doing this would be to introduce a WaitForNewConnection() which would be straightforward as the only way to register for an error event when using select. I proposed the more hackish event flag here instead to avoid having to change the Sock class and its derivatives, and the tests/fuzzers to go with it. I don't think we can have it all here..

Fine. I can live with that, and would be happy to ACK a PR that does only this.

However the hackish way does show its limitations: FuzzedSock's implementation now contradicts EventFlag's documentation because it sets
github.com/bitcoin/bitcoin@dbe9eacd17/src/test/fuzz/util/net.cpp (L434)
whereas the doc says "They share the bits of an Event and are never set in the occurred events."

> Disconnect if we didn't request a read, but we get a hup/error event. This prevents us from reading when we shouldn't because we're paused. Afaik this would be safe to add by itself. That seems fine to do as part of a larger cleanup, but as far as i know this is unrelated to the bug fix from this PR? > Registering for errors when using `select` is harmful in all but one case (detecting connection failures), and in that one it is required. That makes sense to me. I agree with that approach conceptually, even if i dislike the specific implementation in this PR. > As I mentioned above, the less hackish way of doing this would be to introduce a `WaitForNewConnection()` which would be straightforward as the only way to register for an error event when using `select`. I proposed the more hackish event flag here instead to avoid having to change the `Sock` class and its derivatives, and the tests/fuzzers to go with it. I don't think we can have it all here.. Fine. I can live with that, and would be happy to ACK a PR that does only this. However the hackish way does show its limitations: `FuzzedSock`'s implementation now contradicts `EventFlag`'s documentation because it sets https://github.com/bitcoin/bitcoin/blob/dbe9eacd17ae1cc24581081613123a40b44a9f31/src/test/fuzz/util/net.cpp#L434 whereas the doc says "They share the bits of an `Event` and are never set in the occurred events."
theuni commented 2026-11-23 19:19:31 +00:00 (Migrated from github.com)

Disconnect if we didn't request a read, but we get a hup/error event. This prevents us from reading when we shouldn't because we're paused. Afaik this would be safe to add by itself.

That seems fine to do as part of a larger cleanup, but as far as i know this is unrelated to the bug fix from this PR?

Yes, I suppose this is left-over from the version of this PR where Windows still needed to react to errors with disconnects. It's required for other poll impls, but not for Linux. I suppose for the sake of keeping this as narrow in scope as possible, it can be removed.

> > Disconnect if we didn't request a read, but we get a hup/error event. This prevents us from reading when we shouldn't because we're paused. Afaik this would be safe to add by itself. > > That seems fine to do as part of a larger cleanup, but as far as i know this is unrelated to the bug fix from this PR? Yes, I suppose this is left-over from the version of this PR where Windows still needed to react to errors with disconnects. It's required for other poll impls, but not for Linux. I suppose for the sake of keeping this as narrow in scope as possible, it can be removed.
darosior (Migrated from github.com) requested changes 2026-11-23 19:32:20 +00:00
darosior (Migrated from github.com) left a comment

Approach ACK for only setting the exception set when the caller wants connection errors. I would be happy to review a cleaner WaitForConnectionErrors() approach, but i don't mind too much as that code would go once we switch to using poll() everywhere.

That said, i still think this PR is doing way too much:

  • i don't think the test in the first commit should be part of this PR. It does not catch the bug this PR fixes, instead it tests that urgent data does not stall us, which i suppose could be considered on its own, but is unrelated to that PR.
  • the second commit is all we would like to backport, as far as i can tell. It's got a robust unit test that does catch the bug and a minimal fix for the bug.
  • the third commit introduces a test that as far as i understand is unrelated to the bug fix from this PR and contains assumptions about kernel buffer sizes which i think are unnecessarily brittle
  • the fourth commit seems fine to do, but is unrelated to the bug fix. I think it'd be better as part of a larger cleanup discussed in #36761

Can this PR be trimmed down to only the one commit that is relevant to fix this bug, and further cleanups / unrelated testing be considered in followups?

Approach ACK for only setting the exception set when the caller wants connection errors. I would be happy to review a cleaner `WaitForConnectionErrors()` approach, but i don't mind too much as that code would go once we switch to using poll() everywhere. That said, i still think this PR is doing way too much: - i don't think the test in the first commit should be part of this PR. It does not catch the bug this PR fixes, instead it tests that urgent data does not stall us, which i suppose could be considered on its own, but is unrelated to that PR. - the second commit is all we would like to backport, as far as i can tell. It's got a robust unit test that *does* catch the bug and a minimal fix for the bug. - the third commit introduces a test that as far as i understand is unrelated to the bug fix from this PR and contains assumptions about kernel buffer sizes which i think are unnecessarily brittle - the fourth commit seems fine to do, but is unrelated to the bug fix. I think it'd be better as part of a larger cleanup discussed in #36761 Can this PR be trimmed down to only the one commit that is relevant to fix this bug, and further cleanups / unrelated testing be considered in followups?
theuni commented 2026-11-23 20:53:01 +00:00 (Migrated from github.com)

Thanks, @darosior, I think we're finally getting somewhere.

I agree that the second commit is the meat of the issue here.

(I argued above for the change to add the disconnect in the recvRequested && POLLERR | POLLHUP case on poll+Linux, as if it's not currently an issue it's only by luck, but that is indeed independent of the select issue being fixed here)

Thanks, @darosior, I think we're finally getting somewhere. I agree that the second commit is the meat of the issue here. (I argued above for the change to add the disconnect in the `recvRequested && POLLERR | POLLHUP` case on poll+Linux, as if it's not currently an issue it's only by luck, but that is indeed independent of the `select` issue being fixed here)
Sjors commented 2026-11-24 11:49:57 +00:00 (Migrated from github.com)

I opened a followup PR #36963 (draft) and moved all commits except net: only use the select error set while connecting there. Reviewers can use it to better understand the change here, and e.g. see for themselves that its new functional tests pass before the fix too.

Back-porting still (textually) interacts with:

  • f395acdeee scripted-diff: Rename Sock::{RECV,SEND,ERR} (31.x and older)
  • d22d356512 util, cli: name the Sock wait timeout cap and use it for -rpcclienttimeout=0 (all releases)
I opened a followup PR #36963 (draft) and moved all commits except `net: only use the select error set while connecting` there. Reviewers can use it to better understand the change here, and e.g. see for themselves that its new functional tests pass before the fix too. Back-porting still (textually) interacts with: - f395acdeeeaa1f3fd75d3cedbf2731fa24083e9f `scripted-diff: Rename Sock::{RECV,SEND,ERR}` (31.x and older) - d22d3565128828e158c6684a1b5bf1a7f2454c80 `util, cli: name the Sock wait timeout cap and use it for -rpcclienttimeout=0` (all releases)
darosior commented 2026-11-24 15:46:41 +00:00 (Migrated from github.com)

Thanks @Sjors. Reviewing now.

Thanks @Sjors. Reviewing now.
darosior (Migrated from github.com) approved these changes 2026-11-24 16:26:25 +00:00
darosior (Migrated from github.com) left a comment
ACK 1719ea7584dc1ef58506737caa1597e4f5c8bdeb
Lines 162-165
darosior (Migrated from github.com) commented 2026-11-24 16:24:07 +00:00

Hope we can get rid of that soon.. It's confusing and ugly that callers need to know specific implementation details, such as the syscall used on each platform, in order to use the interface correctly.

Hope we can get rid of that soon.. It's confusing and ugly that callers need to know specific implementation details, such as the syscall used on each platform, in order to use the interface correctly.
theuni (Migrated from github.com) approved these changes 2026-11-24 20:02:06 +00:00
theuni (Migrated from github.com) left a comment

ACK 1719ea7584

Thanks @sjors for sticking with this and dealing with being pulled in so many directions.

ACK 1719ea7584dc1ef58506737caa1597e4f5c8bdeb Thanks @sjors for sticking with this and dealing with being pulled in so many directions.
vasild (Migrated from github.com) reviewed 2026-11-25 09:15:31 +00:00
vasild (Migrated from github.com) commented 2026-11-25 09:09:58 +00:00

Hmm, the code in Sock::WaitMany() ignored ErrorEvent in requested events and internally would ask select(2) to check for error events if the caller is interested in RecvEvent.

This PR adds a new flag to tell WaitMany() that it needs to set ErrorEvent. Why not just pass ErrorEvent and stop ignoring it? No caller is passing ErrorEvent, so the un-ignoring will be a no-op. Then change the ConnectToSocket() function to use ErrorEvent, it will be the only caller.

Tuu many words, diff better:

diff --git i/src/netbase.cpp w/src/netbase.cpp
index 7f02fc8912..d414035bff 100644
--- i/src/netbase.cpp
+++ w/src/netbase.cpp
@@ -600,13 +600,13 @@ static bool ConnectToSocket(const Sock& sock,
         // WSAEINVAL is here because some legacy version of winsock uses it
         if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
         {
             // Connection didn't actually fail, but is being established
             // asynchronously. Thus, use async I/O api (select/poll)
             // synchronously to check for successful connection with a timeout.
-            const Sock::Event requested = Sock::RecvEvent | Sock::SendEvent;
+            const Sock::Event requested = Sock::RecvEvent | Sock::SendEvent | Sock::ErrorEvent;
             Sock::Event occurred;
             if (!sock.Wait(timeout, requested, &occurred)) {
                 LogDebug(BCLog::NET, "wait for connect to %s failed: %s",
                           dest_str,
                           NetworkErrorString(WSAGetLastError()));
                 return false;
diff --git i/src/util/sock.cpp w/src/util/sock.cpp
index 8d567b397a..50c94f593a 100644
--- i/src/util/sock.cpp
+++ w/src/util/sock.cpp
@@ -213,18 +213,20 @@ bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per
         if (!sock->IsSelectable()) {
             return false;
         }
         const auto& s = sock->m_socket;
         if (events.requested & RecvEvent) {
             FD_SET(s, &recv);
-            FD_SET(s, &err);
         }
         if (events.requested & SendEvent) {
             FD_SET(s, &send);
         }
-        if (events.requested & (RecvEvent | SendEvent)) {
+        if (events.requested & ErrorEvent) {
+            FD_SET(s, &err);
+        }
+        if (events.requested & (RecvEvent | SendEvent | ErrorEvent)) {
             socket_max = std::max(socket_max, s);
         }
     }
 
     timeval tv = MillisToTimeval(timeout);
 
Hmm, the code in `Sock::WaitMany()` ignored `ErrorEvent` in requested events and internally would ask `select(2)` to check for error events if the caller is interested in `RecvEvent`. This PR adds a new flag to tell `WaitMany()` that it needs to set `ErrorEvent`. Why not just pass `ErrorEvent` and stop ignoring it? No caller is passing `ErrorEvent`, so the un-ignoring will be a no-op. Then change the `ConnectToSocket()` function to use `ErrorEvent`, it will be the only caller. Tuu many words, diff better: ```diff diff --git i/src/netbase.cpp w/src/netbase.cpp index 7f02fc8912..d414035bff 100644 --- i/src/netbase.cpp +++ w/src/netbase.cpp @@ -600,13 +600,13 @@ static bool ConnectToSocket(const Sock& sock, // WSAEINVAL is here because some legacy version of winsock uses it if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { // Connection didn't actually fail, but is being established // asynchronously. Thus, use async I/O api (select/poll) // synchronously to check for successful connection with a timeout. - const Sock::Event requested = Sock::RecvEvent | Sock::SendEvent; + const Sock::Event requested = Sock::RecvEvent | Sock::SendEvent | Sock::ErrorEvent; Sock::Event occurred; if (!sock.Wait(timeout, requested, &occurred)) { LogDebug(BCLog::NET, "wait for connect to %s failed: %s", dest_str, NetworkErrorString(WSAGetLastError())); return false; diff --git i/src/util/sock.cpp w/src/util/sock.cpp index 8d567b397a..50c94f593a 100644 --- i/src/util/sock.cpp +++ w/src/util/sock.cpp @@ -213,18 +213,20 @@ bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per if (!sock->IsSelectable()) { return false; } const auto& s = sock->m_socket; if (events.requested & RecvEvent) { FD_SET(s, &recv); - FD_SET(s, &err); } if (events.requested & SendEvent) { FD_SET(s, &send); } - if (events.requested & (RecvEvent | SendEvent)) { + if (events.requested & ErrorEvent) { + FD_SET(s, &err); + } + if (events.requested & (RecvEvent | SendEvent | ErrorEvent)) { socket_max = std::max(socket_max, s); } } timeval tv = MillisToTimeval(timeout); ```
Sjors (Migrated from github.com) reviewed 2026-11-25 11:58:28 +00:00
Sjors (Migrated from github.com) commented 2026-11-25 11:58:28 +00:00

That does seem more consistent with the original code, i.e. checking events.requested & ErrorEvent the same way check events.requested & RecvEvent and events.requested & SendEvent. And it avoids the new ConnErrorEventFlag.

Implemented in https://github.com/Sjors/bitcoin/pull/135, which I'll study a bit more and then push here if I don't find a new problem.

That does seem more consistent with the original code, i.e. checking `events.requested & ErrorEvent` the same way check `events.requested & RecvEvent` and `events.requested & SendEvent`. And it avoids the new `ConnErrorEventFlag`. Implemented in https://github.com/Sjors/bitcoin/pull/135, which I'll study a bit more and then push here if I don't find a new problem.
Sjors commented 2026-11-25 14:49:29 +00:00 (Migrated from github.com)

I switched to @vasild's approach: https://github.com/bitcoin/bitcoin/pull/36716#discussion_r4692637894

It's simpler, yet as far as I can tell identical in behavior in the current code. It gets rid of the new ConnErrorEventFlag that @darosior didn't like. It also avoids touching the fuzzer and test/util.

Additionally I (well, my agent...) made wait_ignores_urgent_data handle CI memory pressure better:

+    // Do not check that nothing occurred at all: the socket may be reported
+    // as readable. Linux does that for a pending urgent byte while it is
+    // short of memory for socket buffers, until a recv() skips the byte.
     Sock::Event occurred;
     BOOST_REQUIRE(receiver.Wait(100ms, Sock::RecvEvent, &occurred));
-    BOOST_CHECK(occurred == 0);
+    BOOST_CHECK(!(occurred & Sock::ErrorEvent));
 }

I re-ran the Windows (backport) stress test: https://github.com/Sjors/bitcoin/actions/runs/45636345549

I switched to @vasild's approach: https://github.com/bitcoin/bitcoin/pull/36716#discussion_r4692637894 It's simpler, yet as far as I can tell identical in behavior in the current code. It gets rid of the new `ConnErrorEventFlag` that @darosior didn't like. It also avoids touching the fuzzer and test/util. Additionally I (well, my agent...) made `wait_ignores_urgent_data` handle CI memory pressure better: ```diff + // Do not check that nothing occurred at all: the socket may be reported + // as readable. Linux does that for a pending urgent byte while it is + // short of memory for socket buffers, until a recv() skips the byte. Sock::Event occurred; BOOST_REQUIRE(receiver.Wait(100ms, Sock::RecvEvent, &occurred)); - BOOST_CHECK(occurred == 0); + BOOST_CHECK(!(occurred & Sock::ErrorEvent)); } ``` I re-ran the Windows (backport) stress test: https://github.com/Sjors/bitcoin/actions/runs/45636345549
darosior (Migrated from github.com) reviewed 2026-11-25 15:12:46 +00:00
Lines 168-177
darosior (Migrated from github.com) commented 2026-11-25 15:12:46 +00:00

Ok if you are going to make changes here, please update the doc comments not to mention internal syscalls, which do not mean anything on their own to the user of that interface, but the platforms they correspond to, which at least is meaningful to the caller to some extent.

"On Linux, this happens when ... On other platforms (Windows, macOS, BSDs) this happens when ..."

Ok if you are going to make changes here, please update the doc comments not to mention internal syscalls, which do not mean anything on their own to the user of that interface, but the platforms they correspond to, which at least is meaningful to the caller to some extent. "On Linux, this happens when ... On other platforms (Windows, macOS, BSDs) this happens when ..."
darosior (Migrated from github.com) reviewed 2026-11-25 15:16:42 +00:00
Lines 102-143
darosior (Migrated from github.com) commented 2026-11-25 15:16:42 +00:00

If we are giving up the strict check that nothing is reported, i think the synchronisation with the raw calls is not necessary anymore: you can just send two bytes, one urgent and one non-urgent to wake up the wait and assert it reports a RecvEvent and not an ErrorEvent:

diff --git a/src/test/sock_tests.cpp b/src/test/sock_tests.cpp
index 4513b22e2d..ffa9bf526d 100644
--- a/src/test/sock_tests.cpp
+++ b/src/test/sock_tests.cpp
@@ -8,7 +8,6 @@
 #include <test/util/setup_common.h>
 #include <util/sock.h>
 #include <util/threadinterrupt.h>
-#include <util/time.h>
 
 #include <boost/test/unit_test.hpp>
 
@@ -67,8 +66,7 @@ BOOST_AUTO_TEST_CASE(wait_ignores_urgent_data)
     addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
     socklen_t addr_len{sizeof(addr)};
 
-    const SOCKET listener_socket{CreateSocket()};
-    const Sock listener{listener_socket};
+    const Sock listener{CreateSocket()};
     BOOST_REQUIRE_EQUAL(listener.Bind(reinterpret_cast<sockaddr*>(&addr), addr_len), 0);
     BOOST_REQUIRE_EQUAL(listener.Listen(1), 0);
     BOOST_REQUIRE_EQUAL(listener.GetSockName(reinterpret_cast<sockaddr*>(&addr), &addr_len), 0);
@@ -76,29 +74,18 @@ BOOST_AUTO_TEST_CASE(wait_ignores_urgent_data)
     const Sock sender{CreateSocket()};
     BOOST_REQUIRE_EQUAL(sender.Connect(reinterpret_cast<sockaddr*>(&addr), addr_len), 0);
 
-    // Accept without Sock::Accept(), to know the socket to pass to select().
-    const SOCKET receiver_socket = accept(listener_socket, nullptr, nullptr);
-    BOOST_REQUIRE(receiver_socket != INVALID_SOCKET);
-    const Sock receiver{receiver_socket};
+    const auto receiver{listener.Accept(nullptr, nullptr)};
+    BOOST_REQUIRE(receiver);
 
     BOOST_REQUIRE_EQUAL(sender.Send("U", 1, MSG_OOB), 1);
+    BOOST_REQUIRE_EQUAL(sender.Send("x", 1, 0), 1);
 
-    // Wait for the operating system to report the urgent byte as an
-    // exceptional condition on the receiving socket.
-    fd_set exceptions;
-    FD_ZERO(&exceptions);
-    FD_SET(receiver_socket, &exceptions);
-    timeval timeout{MillisToTimeval(1min)};
-    BOOST_REQUIRE_EQUAL(select(receiver_socket + 1, nullptr, nullptr, &exceptions, &timeout), 1);
-
-    // Waiting to receive must not report the urgent byte as an error.
-    //
-    // Do not check that nothing occurred at all: the socket may be reported
-    // as readable. Linux does that for a pending urgent byte while it is
-    // short of memory for socket buffers, until a recv() skips the byte.
+    // Wait for the regular byte sent after the urgent byte. Once it is
+    // readable, the urgent byte has arrived too. Readiness is level-triggered,
+    // so if the urgent byte is ever reported as an error, it is by now.
     Sock::Event occurred;
-    BOOST_REQUIRE(receiver.Wait(100ms, Sock::RecvEvent, &occurred));
-    BOOST_CHECK(!(occurred & Sock::ErrorEvent));
+    BOOST_REQUIRE(receiver->Wait(1min, Sock::RecvEvent, &occurred));
+    BOOST_CHECK(occurred == Sock::RecvEvent);
 }
 
 BOOST_AUTO_TEST_CASE(move_assignment)
If we are giving up the strict check that nothing is reported, i think the synchronisation with the raw calls is not necessary anymore: you can just send two bytes, one urgent and one non-urgent to wake up the wait and assert it reports a RecvEvent and not an ErrorEvent: ```diff diff --git a/src/test/sock_tests.cpp b/src/test/sock_tests.cpp index 4513b22e2d..ffa9bf526d 100644 --- a/src/test/sock_tests.cpp +++ b/src/test/sock_tests.cpp @@ -8,7 +8,6 @@ #include <test/util/setup_common.h> #include <util/sock.h> #include <util/threadinterrupt.h> -#include <util/time.h> #include <boost/test/unit_test.hpp> @@ -67,8 +66,7 @@ BOOST_AUTO_TEST_CASE(wait_ignores_urgent_data) addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); socklen_t addr_len{sizeof(addr)}; - const SOCKET listener_socket{CreateSocket()}; - const Sock listener{listener_socket}; + const Sock listener{CreateSocket()}; BOOST_REQUIRE_EQUAL(listener.Bind(reinterpret_cast<sockaddr*>(&addr), addr_len), 0); BOOST_REQUIRE_EQUAL(listener.Listen(1), 0); BOOST_REQUIRE_EQUAL(listener.GetSockName(reinterpret_cast<sockaddr*>(&addr), &addr_len), 0); @@ -76,29 +74,18 @@ BOOST_AUTO_TEST_CASE(wait_ignores_urgent_data) const Sock sender{CreateSocket()}; BOOST_REQUIRE_EQUAL(sender.Connect(reinterpret_cast<sockaddr*>(&addr), addr_len), 0); - // Accept without Sock::Accept(), to know the socket to pass to select(). - const SOCKET receiver_socket = accept(listener_socket, nullptr, nullptr); - BOOST_REQUIRE(receiver_socket != INVALID_SOCKET); - const Sock receiver{receiver_socket}; + const auto receiver{listener.Accept(nullptr, nullptr)}; + BOOST_REQUIRE(receiver); BOOST_REQUIRE_EQUAL(sender.Send("U", 1, MSG_OOB), 1); + BOOST_REQUIRE_EQUAL(sender.Send("x", 1, 0), 1); - // Wait for the operating system to report the urgent byte as an - // exceptional condition on the receiving socket. - fd_set exceptions; - FD_ZERO(&exceptions); - FD_SET(receiver_socket, &exceptions); - timeval timeout{MillisToTimeval(1min)}; - BOOST_REQUIRE_EQUAL(select(receiver_socket + 1, nullptr, nullptr, &exceptions, &timeout), 1); - - // Waiting to receive must not report the urgent byte as an error. - // - // Do not check that nothing occurred at all: the socket may be reported - // as readable. Linux does that for a pending urgent byte while it is - // short of memory for socket buffers, until a recv() skips the byte. + // Wait for the regular byte sent after the urgent byte. Once it is + // readable, the urgent byte has arrived too. Readiness is level-triggered, + // so if the urgent byte is ever reported as an error, it is by now. Sock::Event occurred; - BOOST_REQUIRE(receiver.Wait(100ms, Sock::RecvEvent, &occurred)); - BOOST_CHECK(!(occurred & Sock::ErrorEvent)); + BOOST_REQUIRE(receiver->Wait(1min, Sock::RecvEvent, &occurred)); + BOOST_CHECK(occurred == Sock::RecvEvent); } BOOST_AUTO_TEST_CASE(move_assignment) ```
darosior (Migrated from github.com) approved these changes 2026-11-25 15:19:50 +00:00
darosior (Migrated from github.com) left a comment

utACK d87ab6523d

utACK d87ab6523de02e1ce33345b585d826d1d9c9cc79
Sjors (Migrated from github.com) reviewed 2026-11-25 16:09:10 +00:00
Lines 102-143
Sjors (Migrated from github.com) commented 2026-11-25 16:09:10 +00:00
I like less code. Re-running some tests now: https://github.com/Sjors/bitcoin/actions/runs/45652336143
Sjors (Migrated from github.com) reviewed 2026-11-25 16:32:03 +00:00
Lines 162-165
Sjors (Migrated from github.com) commented 2026-11-25 16:32:03 +00:00

I overlooked this comment earlier today, but will be fixed in the next push.

I overlooked this comment earlier today, but will be fixed in the next push.
theuni commented 2026-11-25 16:39:08 +00:00 (Migrated from github.com)

This PR adds a new flag to tell WaitMany() that it needs to set ErrorEvent. Why not just pass ErrorEvent and stop ignoring it? No caller is passing ErrorEvent, so the un-ignoring will be a no-op. Then change the ConnectToSocket() function to use ErrorEvent, it will be the only caller.

Fwiw, the reason I opted for the flag rather than using ErrorEvent directly was to obviate to the caller that the only way to receive errors is to specify the "I'm connecting" flag. Imo it's weird to allow callers to request errors when the request is a no-op on Linux and harmful elsewhere in all but one specific case. I agree this is less of a hack, but I think it's more of a footgun.

But I don't feel strongly enough to argue. I'd rather pour that energy into nuking select entirely :)

> This PR adds a new flag to tell `WaitMany()` that it needs to set `ErrorEvent`. Why not just pass `ErrorEvent` and stop ignoring it? No caller is passing `ErrorEvent`, so the un-ignoring will be a no-op. Then change the `ConnectToSocket()` function to use `ErrorEvent`, it will be the only caller. Fwiw, the reason I opted for the flag rather than using `ErrorEvent` directly was to obviate to the caller that the only way to receive errors is to specify the "I'm connecting" flag. Imo it's weird to allow callers to request errors when the request is a no-op on Linux and harmful elsewhere in all but one specific case. I agree this is less of a hack, but I think it's more of a footgun. But I don't feel strongly enough to argue. I'd rather pour that energy into nuking `select` entirely :)
theuni (Migrated from github.com) approved these changes 2026-11-25 16:39:54 +00:00
theuni (Migrated from github.com) left a comment
ACK d87ab6523de02e1ce33345b585d826d1d9c9cc79
Sjors commented 2026-11-25 16:42:28 +00:00 (Migrated from github.com)

I adjusted the ErrorEvent comment and moved some details to src/util/sock.cpp.

Also took @darosior's test shrink.

Sorry @theuni for racing your ACK.

I adjusted the `ErrorEvent` comment and moved some details to `src/util/sock.cpp`. Also took @darosior's test shrink. Sorry @theuni for racing your ACK.
theuni (Migrated from github.com) approved these changes 2026-11-25 16:55:05 +00:00
theuni (Migrated from github.com) left a comment

@Sjors No worries. I'm really not too worried about the details or the tests, as I hope we can get this all deleted soon anyway.

ACK 97e3c95622

@Sjors No worries. I'm really not too worried about the details or the tests, as I hope we can get this all deleted soon anyway. ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6
darosior (Migrated from github.com) approved these changes 2026-11-25 17:03:00 +00:00
darosior (Migrated from github.com) left a comment

re-utACK 97e3c95622

re-utACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6
fanquake (Migrated from github.com) reviewed 2026-11-25 20:51:34 +00:00
fanquake (Migrated from github.com) commented 2026-11-25 20:51:34 +00:00

That keeps it easy to backport: older branches build those for POSIX only.

I don't think we need comments like this. A mention/rationale in the PR or commit message is enough. (not blocking).

> That keeps it easy to backport: older branches build those for POSIX only. I don't think we need comments like this. A mention/rationale in the PR or commit message is enough. (not blocking).
Sjors (Migrated from github.com) reviewed 2026-11-26 07:25:04 +00:00
Sjors (Migrated from github.com) commented 2026-11-26 07:25:04 +00:00

I'll drop it if I need to retouch.

I'll drop it if I need to retouch.
vasild (Migrated from github.com) approved these changes 2026-11-26 13:42:57 +00:00
vasild (Migrated from github.com) left a comment

ACK 97e3c95622

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6
-----BEGIN PGP SIGNATURE-----

iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmsIN0AbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/iUMgAINrMBC/vOpPxgvao3ds
RKdmhU0jipZSXyqeJ7uNPDZU4+aVyVIoJED0akTwyRVbyIL9rvYbvAh+YGiRhqPV
A6EYX3d38kFYt2a6Cwb9H67gn7Mj/MUx0oMPtfMP5RI8NmyLVDbI/3yL59n9LMk0
eZCWmkrZ0+hBiBWX8P5OeFkhI8pu38pyam/FDUIollrYFa+6GQVfF0TLiswdcBZm
MWH3K+60V4podnbvuA0ZAOtEFvXtd55maMaeRIOPQlF40iBYvYaGzSB2aqo/tPrn
KilEhFMzIzlWRZUguEMQKPL+WL67Zb5LjAzFtl++aTRtqqfrw+WfCNluk/C83PpW
afsA+nW/CrbqZVp3z4ymcR4/MHW/tHLhm0lkPX2XfL2uCq97lqKtJCM+2p8yBu8K
m3burEmH1KtR+ecmE6U2Fq9fZOauYJBiGfemnEQxl4Oa8qjd0X6MMysghVSYHFOR
ZQABlzvENmlqcrxSNSyBvme3PtO4/dqLky2U76Gjk8dasO5qDk7+Z7slvZXTn69F
avAzpUdOYgM9Oh6F1JMjas9/iW+b7MreFIZAzSxa513TBDuwFusfzI7fLQ7dicqV
KpvWGCDg7z69LkHCK5OStjn1K79ueNzCbrVKdRK/CQFxNpLEgRcavB7PAbMKPwKI
hCdmwSfLPfqwhI7PaulpXkh2/q2F51ZkBQtvsgprVl6lz4TG/ue3SNilu/mg+/ND
45T8Ux6nGZm5adh1aiD28vGnVF1w/YI6QE17ikToJcKBoL/Ky7xvr85PAKuj9JFt
9/KIu6LOHtow3aXhKkbokWokZNZv5YrGLazXXtzY8R1bbJiy0IzekgHvoMxRDtVR
X6Snf0xkJskCY0U9E68eJGPJTwZBu5cP/VnS439odEYTGn6qwCRN17p7EcyMp0bN
tJEtPr9DqfuLlWZ3DfksMbh31Rq7hSTIGOXFF8NHUVA5dnplVEtavIeccxEpmCEU
j8dajKvMGAbVWRZ4IQc1T1NnRwCUbaDeFxAp5/J1iQm8jWuPh9/F4QqiNR0wewcS
c/cM9XippmzQPRWBFTmhGOOEYdE2zNdZBRSx8+32xlWMPNffoLOcTLiVrB7HpMHA
wXfapSz4T7S0gVPgE8fy9MAmaZLkiviNb6yKzdb4td3CqE9cl6oj7vM8+2AiGS79
9yVpn8rUq8ZZvwAGsVARimKFDxoELscCYZYNxIpdCmi1R8RCBzcyYk6OB/qU3Hxi
4bKcSH11PDhU0YQyfkYT+1AZ1N0yKyWwt0mQLq3esSzpzLcHnW7rKxy4xjjGSgF7
4WtPQSUUxU0JOzNEjPxMBgvYPjR4J9d1XbrAbvIc44VgpSy4lsImXUEYxjr0FzlF
SZU=
=Gw78
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6 <details> <summary>Show Signature</summary> ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6 -----BEGIN PGP SIGNATURE----- iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmsIN0AbFIAAAAAABAAO bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/iUMgAINrMBC/vOpPxgvao3ds RKdmhU0jipZSXyqeJ7uNPDZU4+aVyVIoJED0akTwyRVbyIL9rvYbvAh+YGiRhqPV A6EYX3d38kFYt2a6Cwb9H67gn7Mj/MUx0oMPtfMP5RI8NmyLVDbI/3yL59n9LMk0 eZCWmkrZ0+hBiBWX8P5OeFkhI8pu38pyam/FDUIollrYFa+6GQVfF0TLiswdcBZm MWH3K+60V4podnbvuA0ZAOtEFvXtd55maMaeRIOPQlF40iBYvYaGzSB2aqo/tPrn KilEhFMzIzlWRZUguEMQKPL+WL67Zb5LjAzFtl++aTRtqqfrw+WfCNluk/C83PpW afsA+nW/CrbqZVp3z4ymcR4/MHW/tHLhm0lkPX2XfL2uCq97lqKtJCM+2p8yBu8K m3burEmH1KtR+ecmE6U2Fq9fZOauYJBiGfemnEQxl4Oa8qjd0X6MMysghVSYHFOR ZQABlzvENmlqcrxSNSyBvme3PtO4/dqLky2U76Gjk8dasO5qDk7+Z7slvZXTn69F avAzpUdOYgM9Oh6F1JMjas9/iW+b7MreFIZAzSxa513TBDuwFusfzI7fLQ7dicqV KpvWGCDg7z69LkHCK5OStjn1K79ueNzCbrVKdRK/CQFxNpLEgRcavB7PAbMKPwKI hCdmwSfLPfqwhI7PaulpXkh2/q2F51ZkBQtvsgprVl6lz4TG/ue3SNilu/mg+/ND 45T8Ux6nGZm5adh1aiD28vGnVF1w/YI6QE17ikToJcKBoL/Ky7xvr85PAKuj9JFt 9/KIu6LOHtow3aXhKkbokWokZNZv5YrGLazXXtzY8R1bbJiy0IzekgHvoMxRDtVR X6Snf0xkJskCY0U9E68eJGPJTwZBu5cP/VnS439odEYTGn6qwCRN17p7EcyMp0bN tJEtPr9DqfuLlWZ3DfksMbh31Rq7hSTIGOXFF8NHUVA5dnplVEtavIeccxEpmCEU j8dajKvMGAbVWRZ4IQc1T1NnRwCUbaDeFxAp5/J1iQm8jWuPh9/F4QqiNR0wewcS c/cM9XippmzQPRWBFTmhGOOEYdE2zNdZBRSx8+32xlWMPNffoLOcTLiVrB7HpMHA wXfapSz4T7S0gVPgE8fy9MAmaZLkiviNb6yKzdb4td3CqE9cl6oj7vM8+2AiGS79 9yVpn8rUq8ZZvwAGsVARimKFDxoELscCYZYNxIpdCmi1R8RCBzcyYk6OB/qU3Hxi 4bKcSH11PDhU0YQyfkYT+1AZ1N0yKyWwt0mQLq3esSzpzLcHnW7rKxy4xjjGSgF7 4WtPQSUUxU0JOzNEjPxMBgvYPjR4J9d1XbrAbvIc44VgpSy4lsImXUEYxjr0FzlF SZU= =Gw78 -----END PGP SIGNATURE----- ``` vasild's public key is [on openpgp.org](https://keys.openpgp.org/vks/v1/by-fingerprint/850E138BA9C0923881DFD55FCE712013582E2230) </details>
fanquake commented 2026-11-26 15:20:18 +00:00 (Migrated from github.com)

Backported to 32.x in #36984.

Backported to `32.x` in #36984.
Sjors commented 2026-11-26 16:59:23 +00:00 (Migrated from github.com)

Continued in:

Continued in: - #36963
Sjors (Migrated from github.com) reviewed 2026-11-26 16:59:28 +00:00
Sjors (Migrated from github.com) commented 2026-11-26 16:59:28 +00:00

#36963 drops it

#36963 drops it
pinheadmz (Migrated from github.com) reviewed 2026-11-30 21:10:19 +00:00
pinheadmz (Migrated from github.com) left a comment

post-merge ACK 97e3c95622

This is a nice surgical approach to the issue. We only care about exceptional events when using select() (on Windows) when connecting to a socket. We already have the Error Event flag defined but it has been paired with the Receive Event flag. This patch isolates the exceptional cases to connection, and ignores it in all other cases (like when urgent data is received)

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6
-----BEGIN PGP SIGNATURE-----

iQJPBAEBCAA5FiEE5hdzzW4BBA4vG9eM5+KYS2KJyToFAmsN5R0bFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMCwzAAoJEOfimEtiick6QPEQAI4/yV7xuzeMxmLrC83C
hcwhV/gGnUFv3T3J44V8R+DfE4/n0NBn0EH2KKfShAX7lRv11ev4qnhLmaCTWmEz
/1RQWE3aT5C9JVDApdW41ytYh+Ib9e5pVLlZsJlqyywG3NdqHLXPbpaeswNl/s59
e6+5WEnexut8rWfy8H/yDo2ptYZTmweoPDpUfHiuPXIUYeKMvCv00ZTn7xTWCIEX
gG05phRIuIxvjuC8JUfNCaodOnjGIF7neSJ9f4aliJ+EquwYWqI53RBKwv2hgw4s
QEAtYRfIqwCryvfNF7BHJNYfWwAlrLkegnOGSW04pBMEIwyaK4D/aMGfFogoYYvN
HtO78JmU1H7jfynHenCSPSrSnE0ExFyaCMfcezr2IaQfpzoGGKjN1BFo94UJuJ3u
I95TRuOgYJtaA6f7YG1NTurJQQoS3kKjyNHn1sUose0weWW1dgRW5Nmm4weFE3nV
jZQTIpAnRRIKk0pIzx+VtfgdaX5mai6cP+dRYK5bv/OtWl5QHgYtpkP0aBfxYmgI
USvFFuK+oFOsSUu82ReakOlcRkXrzUXXMwRQnTybD7vsynAdf4DjKuu6jFEKTOTq
2rcrQi7tvd66QzuB98NQJ6keuKPzRx718ycXFYl3zHSDUGt1JcY5b+nplOlOAHG6
turtyhalO5RRXCPmtSdZxeGv
=LfXx
-----END PGP SIGNATURE-----

pinheadmz's public key is on openpgp.org

post-merge ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6 This is a nice surgical approach to the issue. We only care about exceptional events when using `select()` (on Windows) when connecting to a socket. We already have the Error Event flag defined but it has been paired with the Receive Event flag. This patch isolates the exceptional cases to connection, and ignores it in all other cases (like when urgent data is received) <details><summary>Show Signature</summary> ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ACK 97e3c9562291f5bbc2b03fef1c70e4975eb2a8c6 -----BEGIN PGP SIGNATURE----- iQJPBAEBCAA5FiEE5hdzzW4BBA4vG9eM5+KYS2KJyToFAmsN5R0bFIAAAAAABAAO bWFudTIsMi41KzEuMTIsMCwzAAoJEOfimEtiick6QPEQAI4/yV7xuzeMxmLrC83C hcwhV/gGnUFv3T3J44V8R+DfE4/n0NBn0EH2KKfShAX7lRv11ev4qnhLmaCTWmEz /1RQWE3aT5C9JVDApdW41ytYh+Ib9e5pVLlZsJlqyywG3NdqHLXPbpaeswNl/s59 e6+5WEnexut8rWfy8H/yDo2ptYZTmweoPDpUfHiuPXIUYeKMvCv00ZTn7xTWCIEX gG05phRIuIxvjuC8JUfNCaodOnjGIF7neSJ9f4aliJ+EquwYWqI53RBKwv2hgw4s QEAtYRfIqwCryvfNF7BHJNYfWwAlrLkegnOGSW04pBMEIwyaK4D/aMGfFogoYYvN HtO78JmU1H7jfynHenCSPSrSnE0ExFyaCMfcezr2IaQfpzoGGKjN1BFo94UJuJ3u I95TRuOgYJtaA6f7YG1NTurJQQoS3kKjyNHn1sUose0weWW1dgRW5Nmm4weFE3nV jZQTIpAnRRIKk0pIzx+VtfgdaX5mai6cP+dRYK5bv/OtWl5QHgYtpkP0aBfxYmgI USvFFuK+oFOsSUu82ReakOlcRkXrzUXXMwRQnTybD7vsynAdf4DjKuu6jFEKTOTq 2rcrQi7tvd66QzuB98NQJ6keuKPzRx718ycXFYl3zHSDUGt1JcY5b+nplOlOAHG6 turtyhalO5RRXCPmtSdZxeGv =LfXx -----END PGP SIGNATURE----- ``` pinheadmz's public key is [on openpgp.org](https://keys.openpgp.org/vks/v1/by-fingerprint/E61773CD6E01040E2F1BD78CE7E2984B6289C93A) </details>
pinheadmz (Migrated from github.com) commented 2026-11-30 21:03:31 +00:00

And switch to "with select()" below

     * Could be set in the occurred events. With `poll()` this happens when the
And switch to "with `select()`" below ```suggestion * Could be set in the occurred events. With `poll()` this happens when the ```
Sjors (Migrated from github.com) reviewed 2026-12-01 12:18:46 +00:00
Sjors (Migrated from github.com) commented 2026-12-01 12:18:46 +00:00

Absorbed into #36963.

Absorbed into #36963.
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36716
No description provided.