Skip to content

http: Preserve socket errors before unlocking - #37005

Open
natanleung wants to merge 1 commit into
bitcoin:masterfrom
natanleung:http-preserve-socket-errors
Open

natanleung wants to merge 1 commit into
bitcoin:masterfrom
natanleung:http-preserve-socket-errors

Conversation

@natanleung

@natanleung natanleung commented Nov 28, 2026 •

Copy link
Copy Markdown

Fixes #36973.

Background

For Windows MinGW build with DEBUG_LOCKORDER, releasing m_sock_mutex calls std::this_thread::get_id(). This can clear the Windows last-error value to 0 before the HTTP code reads it.

httpserver_tests/http_socket_error_tests test case mock Send() fails on the first call, then succeed on the next call. By clearing the error WSAEWOULDBLOCK, the test server does not retry and instead disconnects, causing the test failure.

Changes

  • Moved the WSAGetLastError() call into the critical sections for socket paths Send() and Recv()
  • Added a new unit test for Recv() in httpserver_tests/http_socket_error_tests

Related work

@DrahtBot

DrahtBot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

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
Concept ACK pinheadmz
Approach ACK winterrdog

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:

  • #36954 (net: make address overlap impossible when relaying addresses by vasild)
  • #35936 (net: reject oversized locators before allocating by l0rinc)
  • #35027 (net: add -outboundbind option for outgoing source address by 8144225309)

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.

@winterrdog winterrdog left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

approach ACK

WSAGetLastError() reads from a thread-local slot, so the http server code needs to read the error before anything else runs on the same thread, otherwise it could get overwritten, just like it happens here. in this case, releasing the lock, m_sock_mutex, does exactly that in debug builds. as a result, a harmless "try again" error (e.g. WSAEWOULDBLOCK) then gets read as 0, which IOErrorIsPermanent treats as permanent and fatal thus dropping the client

so, reading it immediately after either socket API call, while still holding the lock, avoids that. MSDN docs also explicitly recommend doing it this way


also, +1 to Ralph's suggestion, given these new findings. the existing unit tests only simulates failures on Send(), so we would not catch a regression on the Receive() side if the code is changed in an erroneous way, later on

@natanleung

Copy link
Copy Markdown
Author

Thank you for the review @winterrdog.

I have addressed Ralph's suggestion and added a Recv() unit test in http_socket_error_tests.

@pinheadmz

Copy link
Copy Markdown
Member

Concept ACK but some housekeeping about this PR:

  1. PR Description incorrectly says "no tests modified"
  2. Ideally the test commit would come first to assert current behavior, then change the test with the patch
  3. The same logic (unlock before get error) exists in the P2P version of this code in net.cpp which does not have a unit test -- probably the fix should be applied there as well
  4. Style nit, no whitespace is more common in this codebase ie. {WITH_LOCK...)}; not { WITH_LOCK...) };

In general the PR description reads very LLM-y. Read through the https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md then my suggestion would be, completely re-write the PR description without AI assistance. If you can't, it probably means someone else should take over this PR. It's a pretty simple change and closes a pretty simple issue so I'd rather you learn how to be a valuable contributor.

@winterrdog

winterrdog commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

re: #37005 (comment)

  1. Ideally the test commit would come first to assert current behavior, then change the test with the patch

this reminded me of this comment: #36305 (review). sometimes it is the reverse, like in that case. so i had assumed it was OK here. the developer notes support your idea, though

Comment thread src/test/httpserver_tests.cpp Outdated
* After it sends successfully once, it continues to always succeed.
*
* Useful for testing "try again" logic around non-blocking socket Send() failures.
* Recv() returns a recoverable error (WSAEAGAIN) once, without consuming any request bytes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: "once" is a bit ambiguous next to the Send() paragraph. maybe something like:

Suggested change
* Recv() returns a recoverable error (WSAEAGAIN) once, without consuming any request bytes.
* Its first Recv() also returns a recoverable error (WSAEAGAIN) without consuming
* any request bytes, and after that it always succeeds.

what do you think ?

@natanleung

natanleung commented Dec 1, 2026 •

Copy link
Copy Markdown
Author

@pinheadmz Thank you for the feedback and review. I have updated the PR description accordingly and made the minor whitespace nit fix.

@winterrdog The test comment has been updated. I also agree that this is a test-driven change as the open issue #36973 served as the initial premise for the PR. The developer notes were helpful so that I know for next time.

@maflcko

maflcko commented Dec 1, 2026

Copy link
Copy Markdown
Member

@pinheadmz

Copy link
Copy Markdown
Member

Locally confirmed this fix does solve the error described in #36973

@winterrdog

winterrdog commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

from: #37005 (comment):

  1. The same logic (unlock before get error) exists in the P2P version of this code in net.cpp which does not have a unit test -- probably the fix should be applied there as well

shouldn't this be addressed here, as well ?

i think let us do it all here, and backport at once. what do others suggest ?


if other reviewers agree, the PR author can start off with a patch like this:

net.cpp patch
diff --git a/src/net.cpp b/src/net.cpp
index c146f34d52..2f7c83a4ff 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -1648,6 +1648,7 @@ std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const
         if (expected_more.has_value()) Assume(!data.empty() == *expected_more);
         expected_more = more;
         data_left = !data.empty(); // will be overwritten on next loop if all of data gets sent
+        int nErr = 0;
         int nBytes = 0;
         if (!data.empty()) {
             LOCK(node.m_sock_mutex);
@@ -1664,6 +1665,7 @@ std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const
             }
 #endif
             nBytes = node.m_sock->Send(data.data(), data.size(), flags);
+            if (nBytes < 0) nErr = WSAGetLastError();
         }
         if (nBytes > 0) {
             node.m_last_send = NodeClock::now();
@@ -1682,7 +1684,6 @@ std::pair<size_t, bool> CConnman::SocketSendData(CNode& node) const
         } else {
             if (nBytes < 0) {
                 // error
-                int nErr = WSAGetLastError();
                 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
                     LogDebug(BCLog::NET, "socket send error, %s: %s", node.DisconnectMsg(), NetworkErrorString(nErr));
                     node.CloseSocketDisconnect();
@@ -2237,6 +2238,7 @@ void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes,
         {
             // typical socket buffer is 8K-64K
             uint8_t pchBuf[0x10000];
+            int nErr = 0;
             int nBytes = 0;
             {
                 LOCK(pnode->m_sock_mutex);
@@ -2244,6 +2246,7 @@ void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes,
                     continue;
                 }
                 nBytes = pnode->m_sock->Recv(pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
+                if (nBytes < 0) nErr = WSAGetLastError();
             }
             if (nBytes > 0)
             {
@@ -2272,7 +2275,6 @@ void CConnman::SocketHandlerConnected(const std::vector<CNode*>& nodes,
             else if (nBytes < 0)
             {
                 // error
-                int nErr = WSAGetLastError();
                 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
                 {
                     if (!pnode->fDisconnect) {

i think net_tests.cpp is a good home to add the new tests

@natanleung
natanleung force-pushed the http-preserve-socket-errors branch from 55d2fcc to 3b8c543 Compare December 3, 2026 08:33
@natanleung

natanleung commented Dec 3, 2026 •

Copy link
Copy Markdown
Author

Thanks for the feedback.

@winterrdog Applied the same fix to P2P connections and added the same Send() and Recv() test cases.

@maflcko Squashed.

@DrahtBot

DrahtBot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task 32 bit ARM: https://github.com/bitcoin/bitcoin/actions/runs/47067651345/job/144136562068
LLM reason (✨ experimental): build_fail: Compilation of net_tests.cpp fails because -Werror=overloaded-virtual treats a hidden virtual assignment operator warning as an error.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

Leave a comment here, if you need help tracking down a confusing failure.

@natanleung
natanleung force-pushed the http-preserve-socket-errors branch from 3b8c543 to 0409d2e Compare December 3, 2026 20:11

@winterrdog winterrdog left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the PR title needs an update that includes net too, e.g. net, http: Preserve socket errors before unlocking. same goes for the PR description, since the P2P server now gets the same fix as the HTTP server


side note: when i run .\build\bin\test_bitcoin.exe --run_test=net_tests locally, it results in:

Running 22 test cases...
Assertion failed: nThreadsServicingQueue == 0, file ./scheduler.cpp, line 18

i doubt it has sth to do with this PR because the assertion failure happens on master too. anyone with an idea as to why it happens ?

Comment thread src/test/net_tests.cpp
// Second send succeeds on retry.
connman.SocketHandlerPublic();
BOOST_REQUIRE(!node.fDisconnect);
BOOST_REQUIRE_GT(WITH_LOCK(node.cs_vSend, return node.nSendBytes), 0U);

@winterrdog winterrdog Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: > 0 only proves the counter moved, not that the bytes actually reached the socket. IMO, checking the pipe against the counter is stronger:

diff --git a/src/test/net_tests.cpp b/src/test/net_tests.cpp
index 5b946ddbb4..77841e8237 100644
--- a/src/test/net_tests.cpp
+++ b/src/test/net_tests.cpp
@@ -1911,7 +1911,9 @@ BOOST_AUTO_TEST_CASE(socket_error_tests)
     // Second send succeeds on retry.
     connman.SocketHandlerPublic();
     BOOST_REQUIRE(!node.fDisconnect);
-    BOOST_REQUIRE_GT(WITH_LOCK(node.cs_vSend, return node.nSendBytes), 0U);
+    char sent_wire_bytes[32];
+    const ssize_t bytes_in_pipe{pipes->send.GetBytes(sent_wire_bytes, sizeof(sent_wire_bytes))};
+    BOOST_CHECK_EQUAL(static_cast<uint64_t>(bytes_in_pipe), WITH_LOCK(node.cs_vSend, return node.nSendBytes));

     // Queue the same test message for receiving via the socket.
     auto message{NetMsg::Make(NetMsgType::VERACK)};

Comment thread src/test/net_tests.cpp

BOOST_AUTO_TEST_CASE(socket_error_tests)
{
class ErrorSock : public DynSock

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you add a short doc comment atop ErrorSock, like the one in httpserver_tests.cpp ?

it would help future readers see why the first Send()/Recv() fails

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unit tests on Windows with DEBUG_LOCKORDER have been broken for a while

5 participants