From 972e5d72922dc8817c37c89796619d1de4f54e14 Mon Sep 17 00:00:00 2001 From: Timothy Date: Thu, 1 Jul 2021 01:58:34 -0700 Subject: [PATCH] LibCore: Add peer pid retrieval for LocalSocket This will allow programs connected over unix sockets to retrieve the pid of their peers in a nice way. --- Userland/Libraries/LibCore/LocalSocket.cpp | 25 ++++++++++++++++++++++ Userland/Libraries/LibCore/LocalSocket.h | 1 + 2 files changed, 26 insertions(+) diff --git a/Userland/Libraries/LibCore/LocalSocket.cpp b/Userland/Libraries/LibCore/LocalSocket.cpp index 27034e6c41..560a1d036c 100644 --- a/Userland/Libraries/LibCore/LocalSocket.cpp +++ b/Userland/Libraries/LibCore/LocalSocket.cpp @@ -53,6 +53,31 @@ LocalSocket::~LocalSocket() { } +pid_t LocalSocket::peer_pid() const +{ +#ifdef AK_OS_MACOS + pid_t pid; + socklen_t pid_size = sizeof(pid); + + if (getsockopt(fd(), SOL_LOCAL, LOCAL_PEERPID, &pid, &pid_size) < 0) { + dbgln("LocalSocket: getsockopt failed, {}", strerror(errno)); + VERIFY_NOT_REACHED(); + } + + return pid; +#else + struct ucred creds = {}; + socklen_t creds_size = sizeof(creds); + + if (getsockopt(fd(), SOL_SOCKET, SO_PEERCRED, &creds, &creds_size) < 0) { + dbgln("LocalSocket: getsockopt failed, {}", strerror(errno)); + VERIFY_NOT_REACHED(); + } + + return creds.pid; +#endif +} + HashMap LocalSocket::s_overtaken_sockets {}; bool LocalSocket::s_overtaken_sockets_parsed { false }; diff --git a/Userland/Libraries/LibCore/LocalSocket.h b/Userland/Libraries/LibCore/LocalSocket.h index 73c7a89ca1..05b293b0ee 100644 --- a/Userland/Libraries/LibCore/LocalSocket.h +++ b/Userland/Libraries/LibCore/LocalSocket.h @@ -16,6 +16,7 @@ public: virtual ~LocalSocket() override; static RefPtr take_over_accepted_socket_from_system_server(String const& socket_path = String()); + pid_t peer_pid() const; private: explicit LocalSocket(Object* parent = nullptr);