mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 15:11:38 +00:00
http: support unix sockets #36434
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36434
Loading…
Reference in a new issue
No description provided.
Delete branch "http-unix-sockets"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes https://github.com/bitcoin/bitcoin/issues/5029
Accept unix socket paths as options for
-rpcbind=(server) and-rpcconnect=(bitcoin-cli). Options follow the same pattern asipcbind:=unixis a magic keyword that means<datadir>/http.sock=unix:relative/pathmeans<datadir>/relative/path=unix:/absolute/pathmeans/absolute/pathWe delete any existing
http.sockbefore callingbind()and do not clean up at shutdown.Because access is handled by the filesystem,
-rpcallowipis ignored for unix sockets and not required at all if we are only binding to unix sockets.Authentication by username/password/cookie is still required.
A new option
--httpunixis added to the test framework and added to test_runner forrpc_bind.pyandinterface_http.pyfor CI, but (like--usecli) most other tests should also pass with that option. When set, bitcoind is started with-rpcbind=unix...which overridestcp://localhostentirely.AuthProxyhas been extended to connect directly to the unix socket.Try it out!
Refactored code:
Back in https://github.com/bitcoin/bitcoin/pull/27375 we added unix socket support but it was isolated to the
Proxyclass. That created a bit of tech debt which we pay off in this PR. Two new classes are implemented:UnixSocketAddrreflects theCServiceAPI for generic unix sockets, without bitcoin-p2p-specific attributesSocketAddrholds a variant ofUnixSocketAddrandCserviceso classes likeProxyandHTTPServercan operate on an abstract level, with either socket type.CNetAddrandCServiceare left untouched -- they are somewhat dirty combinations of generic socket classes and bitcoin p2p code, adding unix sockets to those classes wouldn't make sense for bitcoin p2p operations and that's why this design was chosen.Follow-up suggestions:
Production code and test framework changes designed and authored by my own cranial meatball. Unit tests added by Opus. C++ cleaned up by Fable, security tightened by Kimi-k3 🧠 🤖 🤖 🤖
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.
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:
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++, andfunc(x, named_arg=0)in Python):src/bitcoin-cli.cpp:Lookup(host, port, /*fAllowLookup=*/true, 256)src/httpserver.cpp:Lookup("::1", http_port, false)src/httpserver.cpp:Lookup("127.0.0.1", http_port, false)src/httpserver.cpp:Lookup(host, port, false)2026-12-01 18:36:07
4 additional verified findings in the Review report.
Earlier concerns neither republished nor resolved: 5 suggestions. See the Run archive linked from the Review report for their assessments.
🟠 Minor · Startup replaces live Unix socket endpoints without reporting a collision
Two nodes using different datadirs but the same custom Unix socket path can silently redirect new clients to the second node rather than reporting an address collision.
Location:
src/netbase.cpp:802(head).🟠 Minor ·
bitcoin-cliTCP connections now apply P2P address filteringThe new
SocketAddr::Connect()validity gate rejects previously attemptedbitcoin-cliTCP destinations such as0.0.0.0; no current in-tree caller using these inputs was found.Location:
src/netbase.cpp:835(head).🟠 Minor ·
interface_http.pydrops the configured connection timeoutreset_conn()discardsnode.rpc_timeout, leaving TCP sockets without an explicit timeout and Unix sockets at 60 seconds regardless of--timeout-factor.Location:
test/functional/interface_http.py:48(head).🟠 Minor · Release note overstates startup failure for non-socket collisions
The release note promises startup failure for a non-socket path, but the inherited partial-bind policy permits startup whenever another
-rpcbindendpoint succeeds.Location:
doc/release-notes-36434.md:21(head).🟠 Minor · Post-bind permission changes follow symlinks
A local user able to replace entries in the socket's parent directory can redirect the post-
bind()pathname permission change to another file owned by the node user.Location:
src/httpserver.cpp:839(head).🟠 Minor · Connection failure can name an address that was never attempted
When a hostname resolves to several addresses and the connection deadline expires early,
bitcoin-clican report an unattempted address alongside an earlier attempt's error.Location:
src/bitcoin-cli.cpp:1297(head).Review coverage was incomplete.
Reviewed:
31a19bf76f9c· Review report · Previous reportspermalink
concept ACK
users of other projects that rely on Core have always wanted sth similar to this and implemented workarounds in the meantime:
there was also an attempt to add this back in 2017:
unfortunately, that attempt ran into a limitation in libevent's HTTP client. supporting Unix Domain sockets in
bitcoin-clirequired a libevent patch to pass an already-open Unix socket connection to the HTTP client. this was eventually addressed in https://github.com/libevent/libevent/pull/1722, but by then Core had decided to moved away from libevent. anyway, with libevent gone, this is no longer an issueDon't forget https://github.com/libevent/libevent/issues/1615 ! Its been a long time coming... now that that pesky little refactor is out of the way we can finally get to it ;-)
concept ACK...i found an issue by running two nodes and noticed that second node can take over a live rpc unix socket path, if two nodes use different datadirs but the same -rpcbind=unix: the second node starts with no error..since it removes the first node socket file and creates its own then after that bitcoin cli talks to the second node.. the first node keeps running but becomes unreachable so with TCP the second bind fails with address already in use
i reproduced this on regtest
1: for node A
2: for node B
3: ss -xlp | grep btc-hijack
4: $CLI stop; sleep 2
5: pgrep -a bitcoind
6: $CLI -rpcwait=0 getblockcount
i noticed a change in bitcoin-cli the host header contains the resolved IP instead of the hostname given in
-rpcconnect=localhostthe build from master sendsHost: localhostbut on this PR sendsHost: 127.0.0.1i reproduced the result by running this py file on terminal 1
on terminal 2 i ran this command
and the output was
🐙 This pull request conflicts with the target branch and needs rebase.
push to
022a6aa69e:"Host:header in bitcoin-cli (@b-l-u-e)Major change is copying the parameter format from
ipcbind, so default is to createhttp.sockin the appropriate network data directory. This should also adderss @b-l-u-e concern about multiple processes messing with each others sockets. Or at least, makes it harder for a user to footgun. Will update the PR description as well.push to
81b8369ac8🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/37798972114/job/113385788562LLM reason (✨ experimental): CI failed because Ruff’s Python lint found an unnecessary
fprefix intest/functional/interface_http.py:758.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.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
push to
c27a1fec1apush to
db638e0f44Fix a test in interface_http made flaky by unix sockets and failed last CI run:
Unix sockets report server closure much faster than TCP which lost a race against the logic where we assert the connection is closed in python by trying to send more data
🐙 This pull request conflicts with the target branch and needs rebase.
approach ACK
i am convinced by the implementation here. particularly, i like the choice of
std::variantover polymorphism (where abstract base classes and vtables are used to determine which behaviour is needed) for theSocketAddrclassafter staring at the implementation for a while now, i think the changes are mostly in very good shape, with the introduction of
SocketAddrbeing the cornerstone change that everything else seems to spring from. most of my reviews have therefore been nitpicks, since i am convinced by the overall design choices. the security is tight too 🔒i have mostly been looking at the implementation C++ code and have not yet had an extensive look at the tests or their infrastructure code, beyond a quick perusal
one last question: i saw
UnixSocketAddr::SetSockAddr()handles empty and abstract namespace addresses, but we do not support binding or connecting to abstract sockets. do you think it is worth supporting them in the future for linux-specific setups ?looks like the PR description is out of sync with the code
it says
=unix:relative/pathresolves to<datadir>/relative/path/http.sockand=unix:/absolute/pathto/absolute/path/http.sock, butResolveUnixSocketAddr()uses the given path as the socket file itself. sounix:rpc.sockturns into<datadir>/rpc.sock, andunix:/tmp/rpc.sockstays/tmp/rpc.sock. only the bareunix(orunix:) keyword uses the defaulthttp.socknamethe docs, release notes and
-helptext already match the code, so i think the PR description just needs updating to reflect this, so other reviewers do not get tripped up by the mismatchi also think this PR would be a good candidate for v33. there has been interest in this for a long time, and i think it is worth tracking as an upcoming feature for the release
TIL: windows has basic support for unix domain sockets (UDS).
since Windows 10 version
1803or later, windows has shipped UDS support but limited toSOCK_STREAMsockets only: https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/nit: sometimes, i see that you use "unix socket", while on other occasions it is "unix domain socket". is that intentional, or should we choose uniformity, pick one option, and then just run with it all throughout ?
"unix socket" seems more common in the docs and in the code comments in this PR's diff, so probably the best candidate to go with.
nit: i think we could
std::moveboth the host string & collection of socket addresses into the returnpairobject (trivial copy avoidance)while reviewing
GetBindAddresses(), i ended up rewriting it to lower the cognitive load a bit and help me get my head around the flow. thought i could share it and see what you think:diff
this is purely a suggestion, so feel free to take or leave it :)
when i went through
GetBindAddresses()andUnixSocketAddr::PreparePath(), i noticed that duplicate unix endpoints can go unnoticed. if two-rpcbindvalues resolve to the same path (e.g.-rpcbind=unixand-rpcbind=unix:http.sock, or the same value inbitcoin.confand perhaps on the command line),PreparePath()(later called inHTTPServer::BindAndStartListening) removes the first socket file before the secondbind(). therefore, both binds succeed without sending a warningis this intentional, or just not something we need to worry about? in the case of TCP, the second bind just fails with
EADDRINUSEand gets logged. would we expect the same here, or is silently rebinding just fine ?strRPCBindcan show up in the logs if the optional port is included in the bind address (e.g.127.0.0.1:8332), leading to logs like this one:Could not bind RPC on address 127.0.0.1:8332 port 8332: Address lookup failed.optional style nit: we could make this a
constinitialised from a ternary expression:why don't we just put this behind an
#ifdef HAVE_SOCKADDR_UNguard so we skip this code entirely on platforms that do not support unix sockets ?sure! we can never get here with a
UnixSocketAddron those platforms anyway, since those addresses get rejected much earlier. currently this would be a no-op at runtime, but we could avoid compiling code that can never be used on those platforms. seems like we can just sidestep it altogether :)charis signed on some platforms (e.g. x86), so bytes above0x7fare interpreted as negative values (they wrap around) and also matchc < 0x20. this means a utf-8 path like/tmp/josé.sockcould end up being replaced with"unix"in the logstaking
unsigned char(evenuint8_tworks OK) in the lambda fixes this (i also switched tostd::rangesin case you find that more appealing)nit: could you have possibly meant this instead ?
push to
e34ffb6de9Rebase on master, fix conflicts from #36509 and #36159
Incorporate lots of great feedback from @winterrdog mostly code clarity and a good catch about signed char's in socket path names
yeah 🤷 we can add windows support for this feature in a follow up
fair point. since "unix domain sockets" is more correct, I'll change any user-facing docs to use that term. code comments and internal phrasing i think is ok to leave alone.
sure, using
movehere for correctnessI think it's a good idea to clean this up now, thanks. Taking the suggestion and tweaking a bit more on top (comments and reducing unreachable code). Adding you as coauthor to that commit.
Heh that's kind of a funny edge case. We don't complain if a user sets
-rpcport=50000twice for example. I think it's ok to leave it. I'm more worried about a user settingipcbindandrpcbindto the same value, but that's a pretty silly mistakefixed this along with the
GetBindAddresses()refactor.sure ternaries are fun! thanks.
yep fair enough, putting behind a compile guard
good suggestion thanks, using
std::rangesandunsigned charherecleaned up this comment.
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/40758721978/job/123064520386LLM reason (✨ experimental): CI failed to compile
test_bitcoin:netbase_tests.cppcallsGetFamily()onProxy, but that method does not exist.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.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
push to
ccbace1c33FIx a test-after-remove rebase mistake that broke ancestor commit CI test
What is the benefit of allowing HTTP over unix sockets compared to using IPC over unix sockets?
executeRpc()is already exposed through IPC.I guess the REST interface is only exposed through HTTP, not IPC.
PR desc typo: isloated
You get the security advantage and possibly an efficiency advantage with a very low bar for entry. IPC requires capnproto, unix sockets only require platform support. IPC is only exposed in multiprocess mode.
See also https://github.com/bitcoin/bitcoin/pull/32297#issuecomment-2813819778
Concept ACK
sth odd is happening here (platform quirks).
on FreeBSD, when you consistently run
./build/test/functional/interface_http.py --httpunix, this test case hangs and later throws aTimeoutErrorerrorlog
the autopsy
the test case assumes that when the server rejects a request and closes the connection, a client blocked in
sendall()should wake up on an error. this happens on Linux and over TCP (on all supported platforms), but not on FreeBSD with unix sockets. so, a client already blocked in a longpoll()is not woken up and it waits out its full socket timeout as a resulti tried to reproduce this similar scenario without
bitcoindi.e. with a plain Python server that never reads and closes after1second which caused the client'ssendall()to time out after10seconds across 4 runs in a deterministic way.reproducer script
bitcoindis closing the connection correctly. the issue appears to be that FreeBSD does not wake an already-blocked client in this scenarioedit: this behaviour does not manifest on netBSD
the same reasoning as before in: https://github.com/bitcoin/bitcoin/pull/36434/changes#r4437730296, it looks like the same issue happens in
check_chunked_transfer()log
on netBSD, this fails with
OSError: [Errno 55] No buffer space availablethe error is caused by setting
SO_SNDBUFto 256 KiB (1 << 18), which netBSD rejects because its default socket buffer limit,kern.sbmax, is also 256 KiB. 128 KiB (1 << 17) works just fine, and so does 256 KiB providedkern.sbmaxis raised above 256 KiBwe could just lower
SO_SNDBUFto 128 KiB so thatinterface_http.py --httpunixpasses end to end on netBSD too. the only thing i am not so sure about is whether 128 KiB is enough for the macOS throttle stall that motivated the 256 KiB in the first placealternatively, we could keep 256 KiB and fall back to 128 KiB on
OSError, but it would be preferable to just keep this simple if 128 KiB is enoughwhat do you think ?
I don't normally use any BSDs but I ran FreeBSD in qemu on my arm64 mac and could not reproduce this test failure. Using this image from https://download.freebsd.org/releases/VM-IMAGES/15.1-RELEASE/aarch64/Latest/FreeBSD-15.1-RELEASE-arm64-aarch64-ufs.qcow2.xz
checked out this branch at
ccbace1c33I get the "expected" outcome in this freebsd vm as well:
error not expected: [Errno 32] Broken pipeoh, that is surprising! because even after restarting and clearing the past build folder, it still times out and breaks at the 2 tests i mentioned. the reproducer python script still times out too with
TimeoutError timed out after 10.0s:(yes, i tested at
ccbace1c33as welli am on FreeBSD
15.0(running via VirtualBox on anx86_64Linux host):anything else about my environment that i might need to provide so that we can come to consensus ?
EDIT: let me push to
15.1(due to15.0's EoL) and then test again, will report back what i find 🤝Really great catch here thank you, I'll take your suggestion to use
1 << 17which I tested on both NetBSD and macos.push to
c01d87c0b2That issue was also caught by running @hebasto nightly BSD tests on this branch:
NetBSD (failed)
FreeBSD (passed)
OpenBSD (passed)
I'll re-run the extra CI tests with this new fix in place
hebasto-nightly CI passed on all 3 BSDs after lowering the buffer size in the test:
on FreeBSD
15.1-RELEASE, all tests pass just like in your case. also, the reproducer script does not time out and passes witherror not expected: [Errno 32] Broken pipelog
the issue ?
it turns out this was a FreeBSD
15.0upstream kernel bug, not a problem with the PRthe issue was that when the server closed a unix-domain socket, the kernel did not wake up a client that was waiting to send, so the client just sat there until its timeout. this is now fixed in
15.1, thus passing all the--httpunixtests on my endall good! this review comment, together with the next one below it, can be marked as resolved
🐙 This pull request conflicts with the target branch and needs rebase.
push to
31a19bf76frebase on master, fix conflicts from https://github.com/bitcoin/bitcoin/pull/36916