libutil: add generic unix socketpair wrapper

previously we used this only for SSH, but other uses may appear soon.

Change-Id: Ibe9666d63aaea07525ebad57decda88b11964cc0
This commit is contained in:
eldritch horrors
2025-07-15 06:40:48 +00:00
parent f4a11d0336
commit e01ae1f453
3 changed files with 36 additions and 18 deletions
+1 -18
View File
@@ -51,24 +51,7 @@ void SSH::addCommonSSHOpts(Strings & args)
std::unique_ptr<SSH::Connection> SSH::startCommand(const std::string & command) std::unique_ptr<SSH::Connection> SSH::startCommand(const std::string & command)
{ {
int sp[2]; auto [parent, child] = SocketPair::stream();
// only linux and bsd support SOCK_CLOEXEC in socketpair type.
#if __linux__ || __FreeBSD__
constexpr int sock_type = SOCK_STREAM | SOCK_CLOEXEC;
#else
constexpr int sock_type = SOCK_STREAM;
#endif
if (socketpair(AF_UNIX, sock_type, 0, sp) < 0) {
throw SysError("socketpair() for ssh");
}
AutoCloseFD parent(sp[0]), child(sp[1]);
#if !(__linux__ || __FreeBSD__)
if (fcntl(parent.get(), F_SETFD, O_CLOEXEC) < 0 || fcntl(child.get(), F_SETFD, O_CLOEXEC) < 0) {
throw SysError("making socketpair O_CLOEXEC");
}
#endif
auto conn = std::make_unique<Connection>(); auto conn = std::make_unique<Connection>();
ProcessOptions options; ProcessOptions options;
options.dieWithParent = false; options.dieWithParent = false;
+23
View File
@@ -9,6 +9,7 @@
#include <cerrno> #include <cerrno>
#include <fcntl.h> #include <fcntl.h>
#include <sys/poll.h> #include <sys/poll.h>
#include <sys/socket.h>
#include <sys/syscall.h> #include <sys/syscall.h>
#include <unistd.h> #include <unistd.h>
@@ -327,4 +328,26 @@ void resetBlockingState(int fd, FdBlockingState prevState)
throw SysError("resetBlockingState"); throw SysError("resetBlockingState");
} }
} }
SocketPair SocketPair::stream()
{
int sp[2];
#ifdef SOCK_CLOEXEC
constexpr int sock_type = SOCK_STREAM | SOCK_CLOEXEC;
#else
constexpr int sock_type = SOCK_STREAM;
#endif
if (socketpair(AF_UNIX, sock_type, 0, sp) < 0) {
throw SysError("socketpair()");
}
AutoCloseFD a(sp[0]), b(sp[1]);
#ifndef SOCK_CLOEXEC
closeOnExec(a.get());
closeOnExec(b.get());
#endif
return {std::move(a), std::move(b)};
}
} }
+12
View File
@@ -83,6 +83,18 @@ public:
void close(); void close();
}; };
struct SocketPair
{
/** The two sides of the socket pair. */
AutoCloseFD a, b;
/** Create a unix stream socket pair with the `O_CLOEXEC` set on both ends. */
static SocketPair stream();
private:
SocketPair(AutoCloseFD a, AutoCloseFD b) : a(std::move(a)), b(std::move(b)) {}
};
/** /**
* Close all file descriptors except stdio fds (ie 0, 1, 2). * Close all file descriptors except stdio fds (ie 0, 1, 2).
* Good practice in child processes. * Good practice in child processes.