RFC: switch from select() to poll() on all platforms #36761

issue darosior opened this issue on November 4, 2026
  1. darosior commented at 5:16 PM on November 4, 2026: member

    CVE-2026-117350 prompted me to look into getting rid of select() in favour of using poll() on all platforms.

    The main advantages of doing this would be to get rid of our artificially low file descriptor limit, and to use the same (security-critical) logic on our less-tested platforms as on our main platform.

    This also allows to get rid of some platform-specific quirks, such as Windows requiring that we register the exception set, therefore subscribing us to be notified of TCP urgent data and causing unwanted behaviour. But this point is in my opinion less salient, as the move would likely trade some platform-specific quirks for some others.

    Work to switch over to poll() was started by @pstratem in #14336, which (thankfully) introduced Linux support. MacOS / BSD support was initially part of the PR, but out of an abundance of caution was then left out after @sdaftuar and @jamesob encountered issues in testing an earlier version of the code. Windows support was not included since WSAPoll was malfunctioning.

    Windows has since fixed WSAPoll in May 2020 (Windows 10 version 2004). BSD always worked. And for macOS, the latest investigation i'm aware of is [that of @jamesob](/bitcoin-bitcoin/14336/#issuecomment-437384408) in #14336. As far as i can tell, the diagnostic that knote_fdfind ignores the difference in filter is incorrect, as kev->filter == kn->kn_filter is checked (link to same commit as James' comment). The misbehaviour seems to be instead caused by how the problematic iteration of the PR listed each socket multiple times, and macOS' poll() implementation collides them in the kqueue (i.e. {fd, POLLIN} followed by {fd, POLLERR|POLLHUP} loses the POLLIN) [^1]. I have verified this by running a reproducer on a macOS VM and having an LLM read the sources.

    I have extensively tested a poll implementation, and ran probes, on macOS, Windows and BSD VMs. So i'm fairly confident poll() support isn't broken on any of these platforms (anymore). However...

    The events reported by poll() sometimes vary depending on the platform, and this is a reason why this is an RFC issue and not a slam-dunk PR. If we are going to refactor the poll() logic to support the different events reported on each platform, we should aim for consistent WaitMany reporting across platforms. But what behaviour do we want?

    I think there is two consistent positions:

    • Fail optimistically. Poll events are only hints. On a read EOF, send whatever we have left before disconnecting. On a write error, read whatever was left in the buffer.
    • Fail closed. Disconnect on any reported event that is not plain readiness, as well as on EOF or a read/write error.

    The former avoids unnecessarily dropping a potentially useful message to/from a peer. The latter doesn't, but helps avoid getting tricked into reading when we shouldn't (CVE-2026-117350) or waking but not being able to make progress (#36688). Bitcoin Core does not strictly follow either, so we don't benefit from always reading/writing as much as possible, and have also exposed ourselves to the aforementioned bugs.

    Our knee jerk reaction after the concerning vulnerability may be to just fail closed everywhere, but we should also consider that we now also use our socket implementation for the HTTP server, for which the opposite behaviour may be preferable (for instance it would make sense to respond to a client that sends a request and closes its side of the connection).

    Thoughts?

    To assist this discussion, here are tables from my probe comparing the events reported by select() today versus what poll() would report for each of FreeBSD / macOS / Windows. For select(): R/W/E means readfds/writefds/exceptfds comes back set. For poll(): IN/OUT/HUP/ERR are just the POLL suffixes.

    FreeBSD

    Peer did select() RecvEvent poll() RecvEvent select() SendEvent poll() SendEvent select() RecvEvent|SendEvent poll() RecvEvent|SendEvent
    idle – – W OUT W OUT
    urgent byte E – W OUT WE OUT
    FIN or graceful close R IN W OUT RW IN OUT
    RST R IN HUP W HUP RW IN HUP
    data R IN W OUT RW IN OUT
    data + urgent byte RE IN W OUT RWE IN OUT
    data + FIN or graceful close R IN W OUT RW IN OUT
    data + RST R IN HUP W HUP RW IN HUP
    failed connect R IN HUP W HUP RW IN HUP

    macOS

    Peer did select() RecvEvent poll() RecvEvent select() SendEvent poll() SendEvent select() RecvEvent|SendEvent poll() RecvEvent|SendEvent
    idle – – W OUT W OUT
    urgent byte E – W OUT WE OUT
    FIN or graceful close R IN HUP W OUT RW IN HUP
    RST R IN HUP W HUP RW IN HUP
    data R IN W OUT RW IN OUT
    data + urgent byte RE IN W OUT RWE IN OUT
    data + FIN or graceful close R IN HUP W OUT RW IN HUP
    data + RST R IN HUP W HUP RW IN HUP
    failed connect R IN HUP W HUP RW IN HUP

    Windows

    Note that on Windows POLLIN corresponds to RDNORM | RDBAND. So requesting POLLIN will ask to be woken up for both events, but checking for a reported POLLIN (reported_event & POLLIN) will match when either of the two is set.

    Peer did select() RecvEvent poll() RecvEvent select() SendEvent poll() SendEvent select() RecvEvent|SendEvent poll() RecvEvent|SendEvent
    idle – – W OUT W OUT
    idle; our send buffer full – – – – – –
    urgent byte E IN W OUT WE IN OUT
    urgent byte; our send buffer full E IN – – E IN
    FIN or graceful close R HUP W OUT HUP RW OUT HUP
    FIN; our send buffer full R HUP – HUP R HUP
    RST R ERR HUP W OUT ERR HUP RW OUT ERR HUP
    data R IN W OUT RW IN OUT
    data; our send buffer full R IN – – R IN
    data + urgent byte RE IN W OUT RWE IN OUT
    data + urgent byte; our send buffer full RE IN – – RE IN
    data + FIN or graceful close R IN HUP W OUT HUP RW IN OUT HUP
    data + FIN; our send buffer full R IN HUP – HUP R IN HUP
    data + RST R ERR HUP W OUT ERR HUP RW OUT ERR HUP
    failed connect E – – OUT ERR HUP E OUT ERR HUP

    [^1]: For more details, here is the call chain that would lead to the observed issue: - Each pollfd becomes a kevent tagged with its array index, and POLLHUP counts as read interest: sys_generic.c#L1745-L1758 - The lookup matches on (kqueue, fd, filter), so a second read registration finds the existing filter: kern_event.c#L6808-L6811 - Re-registering overwrites the filter’s tag with the new entry’s index: kern_event.c#L4249-L4253 - The result goes to the tagged entry, masked by that entry’s own events: sys_generic.c#L1855-L1878

  2. bitcoindev1337 commented at 6:55 PM on November 4, 2026: none

    poll/select essentially must be treated as merely a hint

    correctness is important but so is availability

  3. bitcoin blocked a user on Nov 4, 2026
  4. fanquake added the label Brainstorming on Nov 5, 2026
  5. fanquake added the label Net on Nov 5, 2026
  6. vasild commented at 5:16 PM on November 5, 2026: contributor

    So poll(POLLIN) on Windows would wake up and report urgent data? 😒 What about using poll(POLLRDNORM) on all platforms? Would that be consistent to ignore urgent data on all platforms?

  7. darosior commented at 9:01 PM on November 5, 2026: member

    Yes, substituting POLLIN for POLLRDNORM everywhere would work. I think the bigger issue here is that macOS with poll() returns HUP on a graceful close (when RecvEvent was requested). Versus the current behaviour, this means that because OUT is masked we won't send one last message to the peer before disconnecting. That's probably acceptable, but coupled with the change to immediately disconnect on error being discussed (cc @theuni), this means we would drop whatever the peer sent before closing without reading it. That may be acceptable too, though maybe more for p2p than for http, and that's why i opened this issue: it's not clear to me what behaviour we find acceptable, let alone what behaviour we desire.

  8. theuni commented at 10:49 PM on November 5, 2026: member

    ~Here's what I had in mind: https://github.com/theuni/bitcoin/commits/net-oob-error/~

    ~I implemented that before seeing @darosior's chart. I'll take a look tomorrow and see if my approach aligns with that data.~

    Edit: that attempt just ended up complicating things, disregard.

  9. fanquake added this to the milestone 33.0 on Nov 6, 2026
  10. bitcoin blocked a user on Nov 7, 2026
  11. bitcoin deleted a comment on Nov 7, 2026
  12. theuni commented at 6:01 PM on November 17, 2026: member

    Concept ACK. When trying to understand everything that's going on in #36716, it's clear that supporting select and poll is problematic, as they differ just enough in behavior to be dangerous.

    Now that we've used poll for Linux for years, and assuming the macos/windows kinks are no longer relevant, I think it makes sense to move forward with nuking select. I imagine we can come up with a set of in/out events that works everywhere, but we can always resort to ifdef hacks if we have to.

  13. theuni commented at 6:19 PM on November 17, 2026: member

    I think the bigger issue here is that macOS with poll() returns HUP on a graceful close (when RecvEvent was requested). Versus the current behaviour, this means that because OUT is masked we won't send one last message to the peer before disconnecting.

    Imo that could be addressed by considering a HUP to be a read event rather than an error.

    diff --git a/src/util/sock.cpp b/src/util/sock.cpp
    index 1e7c13e3def..c333264fdff 100644
    --- a/src/util/sock.cpp
    +++ b/src/util/sock.cpp
    @@ -189,3 +189,3 @@ bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per
             events.occurred = 0;
    -        if (pfds[i].revents & POLLIN) {
    +        if (pfds[i].revents & (POLLIN | POLLHUP)) {
                 events.occurred |= RecvEvent;
    @@ -195,3 +195,3 @@ bool Sock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per
             }
    -        if (pfds[i].revents & (POLLERR | POLLHUP)) {
    +        if (pfds[i].revents & POLLERR {
                 events.occurred |= ErrorEvent;
    

    Imo that better represents with a HUP means.

    In my tests on Linux, though, POLLERR (I think it's POLLHUP|POLLERR to be specific) is emitted when a remote does a full close, so catching the HUP doesn't do much good.

    Of course, we could always fix our client-side to do a proper half-close, but I think that's out-of-scope for this discussion.

  14. theuni commented at 11:12 PM on November 18, 2026: member

    I've pushed a POC branch on top of #36716 that attempts a minimal changeset to switch to poll on all platforms: https://github.com/theuni/bitcoin/tree/net-use-poll-everywhere

    It's missing documentation updates and the actual removal of select. I just wanted to hack it up while I had all the gnarly details paged back into my brain.

  15. fanquake commented at 11:23 AM on November 19, 2026: member

    Concept ACK

  16. darosior commented at 9:06 PM on November 19, 2026: member

    I've pushed a POC branch on top of #36716 that attempts a minimal changeset to switch to poll on all platforms: https://github.com/theuni/bitcoin/tree/net-use-poll-everywhere

    You use the same bit for HUPEvent than for ErrorEvent. I know it's a quick PoC, but even without that typo, i think this branch reintroduces the spin on Windows, because Windows treats a POLLIN registration as RDNORM | RDBAND (as per discussion above), and in your branch RDBAND would lead to a recv() that does not progress. This approach also requires each caller to handle a new hang-up event, and i'm pretty sure this introduces busy loops on Windows (which can report HUP alone) in I2P / SOCKS5 and the HTTP server since it is not handled there.

    I agree with the approach of 1) having callers check for and disconnect on ErrorEvent and 2) on HUP returning a RecvEvent iff RecvEvent was requested and returning an ErrorEvent otherwise.

    I have mixed feelings about adding more special cases that callers need to handle. I'd much rather we have a simple contract "you must check for ErrorEvent and disconnect if it's set", and decide when to return ErrorEvent based on what poll() returns in a single place in Sock::Wait(Many), and not leak specific errors to callers in the form of HupEvent or ConnErrorEventFlag.

    Here is what i was experimenting with locally, updated to have callers always disconnect on ErrorEvent, and to return Recv/Error on hang-ups: https://github.com/darosior/bitcoin/tree/2610_ditch_select.

  17. darosior commented at 9:17 PM on November 19, 2026: member

    Also, i think #36737 and #36786 are pretty useful in testing the various approaches. Rebasing on top of them checks some invariants and explicit some of the behaviour changes. For instance, here is my own approach rebased on top of the tests, with each behaviour changing commit adapting the related tests: https://github.com/darosior/bitcoin/tree/2610_ditch_select_tests.

  18. theuni commented at 10:07 PM on November 19, 2026: member

    I've pushed a POC branch on top of #36716 that attempts a minimal changeset to switch to poll on all platforms: https://github.com/theuni/bitcoin/tree/net-use-poll-everywhere

    You use the same bit for HUPEvent than for ErrorEvent.

    Heh. Forgot to fix that before I pushed. I should've called this a WIP rather than a POC.

    I know it's a quick PoC, but even without that typo, i think this branch reintroduces the spin on Windows, because Windows treats a POLLIN registration as RDNORM | RDBAND (as per discussion above), and in your branch RDBAND would lead to a recv() that does not progress.

    Thanks for taking a look in detail. I had a whole system of hacks trying to get macos/linux synced up with the OOB data, but ultimately mac's impl just refuses to do the right thing, so I just punted on that for later. Windows makes this even more frustrating. I'm starting to wonder if you were right all along about SO_OOBINLINE.

    This approach also requires each caller to handle a new hang-up event, and i'm pretty sure this introduces busy loops on Windows (which can report HUP alone) in I2P / SOCKS5 and the HTTP server since it is not handled there.

    Probably so, yeah. For now I'm just hacking on the p2p side of things to find an incantation that works. I figured we could just migrate that to the other users when we get one.

    I agree with the approach of 1) having callers check for and disconnect on ErrorEvent and 2) on HUP returning a RecvEvent iff RecvEvent was requested and returning an ErrorEvent otherwise.

    I have mixed feelings about adding more special cases that callers need to handle. I'd much rather we have a simple contract "you must check for ErrorEvent and disconnect if it's set", and decide when to return ErrorEvent based on what poll() returns in a single place in Sock::Wait(Many), and not leak specific errors to callers in the form of HupEvent or ConnErrorEventFlag.

    My intention with keeping these separated is to allow buffers to continue to be drained when possible rather than immediately disconnecting (or as a side-effect of a write). Perhaps you're right and no distinction is necessary, but I've found it helpful to keep them separate while hacking.

    Here is what i was experimenting with locally, updated to have callers always disconnect on ErrorEvent, and to return Recv/Error on hang-ups: https://github.com/darosior/bitcoin/tree/2610_ditch_select.

    Thanks, will compare approaches tomorrow.

  19. ajtowns commented at 2:24 AM on November 20, 2026: contributor

    But what behaviour do we want?

    Isn't the behaviour that we want:

    • wake up for read, but nothing to read: consider read-side closed, stop trying to read (connection closes once we finish writing, or once we timeout on waiting for a ping response?)
    • wake up for write, but writing fails: drop connection (or possibly half-close it on our side to attempt to finish reading)
    • write buffer is not empty, and haven't woken up for write for this peer in $TIMEOUT seconds: drop connection

    and we only use the poll flags to route to Recv() or Send() (and always route to one or the other or both on wakeup), and it's the result of those functions that determine the actual error condition? ie the only condition we should be checking is "are we able to make progress on each wakeup" with failure to be able to make progress being the error condition that triggers closure.

    I think it makes sense to move forward with nuking select.

    +1

    If we want to do better than what poll() gets us, I think we should be moving to platform specific util/sock implementations. I think that's probably unnecessary if we're a strict about ensuring we always make progress on wakeups though.

  20. darosior commented at 5:11 PM on November 24, 2026: member

    and we only use the poll flags to route to Recv() or Send() (and always route to one or the other or both on wakeup), and it's the result of those functions that determine the actual error condition? ie the only condition we should be checking is "are we able to make progress on each wakeup" with failure to be able to make progress being the error condition that triggers closure.

    Yes, with the exception of ErrorEvent, which we can use when an error occurs but we can't make more progress, for instance because receive is paused. At this point i think the next best thing to do is to just disconnect.

    So concretely for my branch i think it would mean also returning a RecvEvent when POLLERR is raised (and RecvEvent was requested).

    We could consider better supporting half closes after that, but it's not clear to me that the complexity would be worth it. I think the next best thing would be to better support actually processing the message that are read on a drain. I believe currently it's extremely racy:

    • First, most of our peers run Core, which never half-closes with shutdown() and doesn't drain before closing a connection it decided to drop. Which means we will only get a FIN if we are lucky (and only get a RST after our next send()), but in most cases we'll get an RST right away. Once the RST is in, any send() fails and we disconnect before reading further, since we send first.
    • Second, and that's the big one, the message handler thread must consume any read message between the socket thread's final recv() and it setting fDisconnect.

    In practice, especially with many peers where cycling over all peers' messages takes longer than cycling over all peers' data to read, i think we are far from reliably processing messages sent right before the connection is closed (especially large messages, which i am quite confident we virtually never process).

  21. darosior commented at 12:30 AM on November 26, 2026: member

    I'd like to share one issue i've been discussing with Cory.

    On macOS, poll() follows POSIX and treats HUP and OUT as mutually exclusive (see table in OP). Linux does not. On a peer's graceful close, macOS will report HUP while Linux will report IN | OUT. That means on Linux we'd try to send first, whereas on macOS we'd recv() and hit EOF immediately. This was detected by this test failure.

    There are different ways we could deal with this. I'm currently leaning toward accepting the slight (and harmless) behaviour difference between platforms (it's one of several). Another option could be to try to always report the subset of events that would be reported on all platforms, to minimize platform inconsistencies. The downside would be of course that we start modifying the behaviour on Linux, rather than adapt all platforms to it.

    Thoughts?

  22. darosior commented at 12:40 AM on November 26, 2026: member

    From the same probe data used in OP, here are tables of events returned by poll() on each platform, depending on the requested events and the state of the peer. Presenting the data like so helps spotting inconsistencies and i think can assist the discussion here.

    We ask for POLLRDNORM rather than POLLIN as per my branch and discussions above. A dash means nothing is returned.

    <details> <summary>Requested: RecvEvent (POLLRDNORM)</summary>

    Peer state Linux macOS FreeBSD Windows
    idle – – – –
    idle; our send buffer full – – – –
    data RDNORM RDNORM RDNORM RDNORM
    data; our send buffer full RDNORM RDNORM RDNORM RDNORM
    FIN / graceful close RDNORM RDNORM HUP RDNORM HUP
    FIN; our send buffer full RDNORM RDNORM HUP RDNORM HUP
    data + FIN RDNORM RDNORM HUP RDNORM RDNORM HUP
    data + FIN; our send buffer full RDNORM RDNORM HUP RDNORM RDNORM HUP
    RST RDNORM ERR HUP RDNORM HUP RDNORM HUP ERR HUP
    listening, idle – – – –
    listening, pending connection RDNORM RDNORM RDNORM RDNORM
    connect() in progress – – – –
    connect() succeeded – – – –
    connect() refused RDNORM ERR HUP RDNORM HUP RDNORM HUP –
    closed descriptor NVAL NVAL NVAL poll error

    </details>

    <details> <summary>Requested: SendEvent (POLLOUT)</summary>

    Peer state Linux macOS FreeBSD Windows
    idle OUT OUT OUT OUT
    idle; our send buffer full – – – –
    data OUT OUT OUT OUT
    data; our send buffer full – – – –
    FIN / graceful close OUT OUT OUT OUT HUP
    FIN; our send buffer full – – – HUP
    data + FIN OUT OUT OUT OUT HUP
    data + FIN; our send buffer full – – – HUP
    RST OUT ERR HUP HUP HUP OUT ERR HUP
    listening, idle – – – –
    listening, pending connection – – – –
    connect() in progress OUT OUT – OUT
    connect() succeeded OUT OUT OUT OUT
    connect() refused OUT ERR HUP HUP HUP OUT ERR HUP
    closed descriptor NVAL NVAL NVAL poll error

    </details>

    <details> <summary>Requested: RecvEvent|SendEvent (POLLRDNORM|POLLOUT)</summary>

    Peer state Linux macOS FreeBSD Windows
    idle OUT OUT OUT OUT
    idle; our send buffer full – – – –
    data RDNORM OUT RDNORM OUT RDNORM OUT RDNORM OUT
    data; our send buffer full RDNORM RDNORM RDNORM RDNORM
    FIN / graceful close RDNORM OUT RDNORM HUP RDNORM OUT OUT HUP
    FIN; our send buffer full RDNORM RDNORM HUP RDNORM HUP
    data + FIN RDNORM OUT RDNORM HUP RDNORM OUT RDNORM OUT HUP
    data + FIN; our send buffer full RDNORM RDNORM HUP RDNORM RDNORM HUP
    RST RDNORM OUT ERR HUP RDNORM HUP RDNORM HUP OUT ERR HUP
    listening, idle – – – –
    listening, pending connection RDNORM RDNORM RDNORM RDNORM
    connect() in progress OUT OUT – OUT
    connect() succeeded OUT OUT OUT OUT
    connect() refused RDNORM OUT ERR HUP RDNORM HUP RDNORM HUP OUT ERR HUP
    closed descriptor NVAL NVAL NVAL poll error

    </details>

    (Tables edited to correct a mistake AJ found)

    This makes clear that using the intersection of what's reported on all platforms, although already hacky, is sometimes not even possible as that intersection would be empty. So we would have to use the intersection at the level of our own events, which creates even more complexity.

  23. ajtowns commented at 3:26 AM on November 26, 2026: contributor

    We could consider better supporting half closes after that, but it's not clear to me that the complexity would be worth it.

    we should also consider that we now also use our socket implementation for the HTTP server, for which the opposite behaviour may be preferable

    I think half closes are only really interesting for http/rpc/rest? Finishing reading what we can on p2p when the other side closes the connection is a nice to have, but shouldn't be relied upon or guaranteed, and doesn't really justify any extra complexity? If you want to guarantee receipt, you keep the connection fully open, send a ping with a fresh nonce and wait for the corresponding pong.

    • Second, and that's the big one, the message handler thread must consume any read message between the socket thread's final recv() and it setting fDisconnect.

    I don't think that point makes sense: setting fDisconnect should still lead directly to ~Sock() rather than a half-close -- we don't want any further processing of incoming messages, queued or otherwise, because we set fDisconnect on misbehaviour/potential DoS. Could introduce an fFinishUp distinct from fDisconnect for milder cases where the idea is just to free up a connection slot. But that doesn't seem very valuable -- it would just change where the protocol gets artificially cutoff without really adding any more reliability or saving any significant bandwidth, etc? Might be nice to flush any queued writes, possibly only until send() would block? But again, not much benefit.

    If we want to support half closing sockets ourselves (for bitcoin-cli HTTPClient?), I think that would be introducing a Sock::CloseSend() which would (a) do the half-close, (b) make future Send() calls be a no-op or immediate error, and (c) continue handling Recv() as normal?

    idle; our send buffer full – OUT OUT –

    Something seems wrong with your test there -- if we're not able to write ("our send buffer full"), poll shouldn't be returning OUT ("Normal data may be written without blocking." per FreeBSD manpage)?

    Otherwise, I think:

    • revents & NVAL or poll error; socket is already closed, not sure that shouldn't be an assert failure?
    • revents & (RDNORM | HUP | ERR) results in a RecvEvent and calling Recv(), and stop querying for RDNORM if Recv() returns 0 bytes
    • revents & (OUT | ERR) results in a SendEvent and calling Send() and closing the socket if Send() errors or accepts 0 bytes

    ought to work, provided the "poll(OUT) / FIN; our send buffer full" case only returns "HUP" on windows once, and doesn't busy loop. That would automatically drain on half-close, I believe. It wouldn't necessarily automatically drain the recv buffer on RST (a partial read followed by a send failure would kill the socket), but that seems fine to me.

  24. darosior commented at 10:46 PM on November 28, 2026: member

    I don't think that point makes sense

    I think we're talking about different cases. I agree that when we set fDisconnect ourselves (misbehaviour), nothing more should be processed. My point was about closes initiated by the peer: the socket thread drains what it can, hits EOF/error and sets fDisconnect itself, and whatever messages it read but the message handler hadn't processed yet are dropped. If we were to add complexity, making that reliable seems more useful to me than supporting half-closes.

    If we want to support half closing sockets ourselves (for bitcoin-cli HTTPClient?), I think that would be introducing a Sock::CloseSend() which would (a) do the half-close, (b) make future Send() calls be a no-op or immediate error, and (c) continue handling Recv() as normal?

    Yes, it's not clear to me that it's useful, but that seems doable for bitcoin-cli. For p2p you'd have to split fDisconnect which is currently used both to trigger a disconnect and to signal "are we done with this peer", into multiple states "disconnect this peer", "stream to the peer closed" and "stream from the peer closed", and update every check on fDisconnect to use the appropriate one instead. Again, doesn't seem worth it to me.

    Something seems wrong with your test there

    Yes. It was a bug in the probe, good catch.

    • revents & NVAL or poll error; socket is already closed, not sure that shouldn't be an assert failure?

    Yes! My updated branch has it as an Assume() (not an assert, as if a bug down the road makes NVAL reachable, i believe it's preferable that it enables a spin than a crash).

    • revents & (RDNORM | HUP | ERR) results in a RecvEvent and calling Recv(), [...]

    Ok, so if i understand correctly you suggest that would be safe because RDNORM would only be return by poll() if we asked for it, which we don't if the peer is paused for receiving.

    That would read past our max receive buffer on error though. It's fine because it's bounded by the kernel's receive buffer, but i think it's nice to have the invariant "we never read past our max receive buffer". And keeping that invariant here doesn't cost us much: we only drain up to our max receive buffer of data from the socket of a peer that hammers us and disconnects right away.

    So i think it's cleaner to return an ErrorEvent if RecvEvent was not requested and poll() reports an error.

    • [...] and stop querying for RDNORM if Recv() returns 0 bytes

    That would be trying to support half-close, in one direction. Once we know it won't send anything to us anymore, i don't think it's worth keeping around a peer for 20 more minutes. Unless you are suggesting supporting it for the HTTP server? If so, i'm not convinced there is enough benefit to supporting it there to justify the complexity (since presumably we'd disable it for p2p, and this would mean more different code paths).

    • [...] revents & (OUT | ERR) results in a SendEvent and closing the socket if Send() errors or accepts 0 bytes

    If we had anything to send, that would prevent draining on connection resets on macOS and BSDs (Linux and Windows already report OUT in these cases). Now, that would not be a regression from today since select() always return a writable event in that case.

    So (when we have something to send for that peer) that's akin to the fail-closed behaviour i described, except by routing an error to a syscall that must fail instead of always returning ErrorEvent on error.

    ought to work, provided the "poll(OUT) / FIN; our send buffer full" case only returns "HUP" on windows once, and doesn't busy loop.

    With HUP routed to Recv() it doesn't spin: Recv() returns EOF and we close. It also doesn't address the macOS inconsistency i pointed above: on a graceful close macOS reports HUP without OUT, so we'd still recv() and hit EOF without sending, unlike on Linux. I think just accepting the inconsistency is the way to go, but it's one downside worth discussing.


    To be clear what i suggest (and have implemented) is:

    • revents & RDNORM: report a RecvEvent
    • revents & (HUP | ERR) and RecvEvent was requested: report a RecvEvent
    • revents & (HUP | ERR) and RecvEvent was not requested: report an ErrorEvent
    • revents & OUT: report a SendEvent
    • Assume(!(revents & ~(RDNORM | OUT | ERR | HUP)))
  25. ajtowns commented at 4:15 AM on November 30, 2026: contributor

    To be clear what i suggest (and have implemented) is:

    * `revents & RDNORM`: report a `RecvEvent`
    
    * `revents & (HUP | ERR)` and `RecvEvent` was requested: report a `RecvEvent`
    
    * `revents & (HUP | ERR)` and `RecvEvent` was not requested: report an `ErrorEvent`
    
    * `revents & OUT`: report a `SendEvent`
    
    * Assume(`!(revents & ~(RDNORM | OUT | ERR | HUP))`)

    Yeah, that's roughly what I was thinking except for two things:

    • RecvEvent vs ErrorEvent is differing only on RecvEvent was requested, but that's something the caller can already check via recvReq = it->second.requested & Sock::RecvEvent
    • Having an Assume(platform is not being weird) doesn't seem very useful to me -- because platforms will be weird and we need to cope, and because assume only has an effect on developer/CI builds, and the weird platforms tend to be things users use rather than developers. I think "every event is classified as recv or send; recv event with nothing to recv, or write event with nothing to write causes the socket to close" is a better approach, and avoids the need for an assume. Recv/Send failure leading to close should be both the normal path when everything works correctly and the failure path when someone is doing weird things.

    If you want an error event, I'd be tempted to make that be:

        if (sock.m_socket == INVALID_SOCK || revents & (ERR | NVAL)) {
            events.occurred = ErrorEvent; // no recv/send
            sock.Close();
        }
    

    That would be trying to support half-close, in one direction. [...] Unless you are suggesting supporting it for the HTTP server?

    Yes, I don't think it's at all worthwhile for p2p; I was only suggesting supporting it for the http server/client. That was based on misunderstanding the standard/best-practices, though; I believe the standard actually says that if a client half-closes then the server should just stop processing, so that isn't something that needs special processing; and conversely if the client is well-behaved and sends a "Connection: close" header, and doesn't continue sending any data after that, there's no need for the server side to go out of its way to do a half-close (though that is recommended). So I don't think there is any change necessary there either.

    (However, I think our HTTPServer implementation violates RFC9112's: "A server that receives a "close" connection option ... MUST NOT process any further requests received on that connection." -- recommended behaviour is to recv() and discard; our behaviour is to respond to the request)

    That would read past our max receive buffer on error though.

    Reading past our max receive buffer on error is already what we do in the if (recvSet || errorSet) branch currently though? We also overfill it before setting fPauseSend in the first place. I think it's better for the caller to handle that, than the Sock layer, either by reading a little too much (5MB limit + up to 128kB overrun) as now, or perhaps by checking for fPauseSend or !recvReq and either immediately closing or just not calling Recv until a future poll returns after the current buffer was cleared out.

    I think just accepting the inconsistency is the way to go, but it's one downside worth discussing.

    I think we could go with:

    • we will process all the data on a connection, provided:
      • we send a "i won't send any more data" message ("Connection: close" in http) (and follow through on that)
      • we process their response before closing the connection in any way
      • they only send a FIN after sending their response to our "no more data" message
    • otherwise, a closed connection (FIN or RST) can cause data delivery/processing failures

    We could consider adding an explicit "QUIT" message on the p2p side to fill that pattern, I guess?

  26. darosior commented at 3:54 PM on December 3, 2026: member

    There is a conceptual simplicity to having only two events Read and Write, but only if each has a single meaning, "you may read now" and "you may write now". I think we also want another meaning: "you must disconnect now". And this means we don't get the simplification, quite the opposite, as it would overload the meaning of one of the events.

    As you suggest, it's probably fine to rely on recv() eventually leading to disconnection, and return RecvEvent on ERR | HUP, since the read past our limit is bounded and is the current behaviour[^1]. But for coping with unexpected events ("platform is being weird"), that's not possible. Returning RecvEvent there risks exposing us to the OOM we just patched, so we need to disconnect.

    I think this is better achieved with an explicit ErrorEvent documented as "you must disconnect when this happens", than by having every caller re-implement the check for a reported but unrequested RecvEvent. The latter overloads the meaning of RecvEvent and makes the interface easier to misuse. Better to keep that check in a single place.

    That said, your approach of keeping only Read and Write could work without overloading either if we simply returned nothing on unexpected events. Mapping them to Read and risking an OOM would be pushing it, but if the worst case for something that should be unreachable is a spin until the connection is closed, that seems fine too.

    Regardless, i think having an Assume() is still useful to detect those unexpected events whenever we can. But at this point that's a nit that should rather be discussed on a PR i think.

    If you want an error event, I'd be tempted to make that be:

    I don't think that makes sense. First of all NVAL itself means the descriptor isn't open. But more importantly, i think it's redundant, since the caller still needs to handle the ErrorEvent and drop the connection. It's also a layer violation (i think it's good to keep the wait methods const) and is racy.

    [^1]: I'd still rather we never read past our limits, but that can be broken down into a follow up on its own merits: first make the switch to poll on all platforms match the current behaviour, and then possibly improve over that.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-12-05 04:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me