Skip to content

Get client process id over ip/port when server runs on UNIX socket. #1418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions httplib.h
Original file line number Diff line number Diff line change
Expand Up @@ -2602,6 +2602,9 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port,
hints.ai_addrlen = static_cast<socklen_t>(
sizeof(addr) - sizeof(addr.sun_path) + addrlen);

fcntl(sock, F_SETFD, FD_CLOEXEC);
if (socket_options) { socket_options(sock); }

if (!bind_or_connect(sock, hints)) {
close_socket(sock);
sock = INVALID_SOCKET;
Expand Down Expand Up @@ -2872,6 +2875,24 @@ inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {

if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
&addr_len)) {
#ifndef _WIN32
if (addr.ss_family == AF_UNIX) {
#if defined(__linux__)
struct ucred ucred;
socklen_t len = sizeof(ucred);
if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
port = ucred.pid;
}
#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__
pid_t pid;
socklen_t len = sizeof(pid);
if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
port = pid;
}
#endif
return;
}
#endif
get_remote_ip_and_port(addr, addr_len, ip, port);
}
}
Expand Down
25 changes: 25 additions & 0 deletions test/test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5344,6 +5344,31 @@ TEST_F(UnixSocketTest, pathname) {
t.join();
}

#if defined(__linux__) \
|| /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
TEST_F(UnixSocketTest, PeerPid) {
httplib::Server svr;
std::string remote_port_val;
svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
res.set_content(content_, "text/plain");
remote_port_val = req.get_header_value("REMOTE_PORT");
});

std::thread t {[&] {
ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80)); }};
while (!svr.is_running()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ASSERT_TRUE(svr.is_running());

client_GET(pathname_);
EXPECT_EQ(std::to_string(getpid()), remote_port_val);

svr.stop();
t.join();
}
#endif

#ifdef __linux__
TEST_F(UnixSocketTest, abstract) {
constexpr char svr_path[] {"\x00httplib-server.sock"};
Expand Down