From 30abb7234de2a9caa1add4b00a189436f0b24560 Mon Sep 17 00:00:00 2001 From: Kenny Root Date: Tue, 14 Sep 2010 14:26:12 -0700 Subject: [PATCH] Fetch peer credentials for local sockets Fetch the PID, UID, and GID of the remote side of a local socket connection in case any users of this library class want to check it. Change-Id: Ia3230e6bc68ab6f93160df9f5996d2bf744b872c --- include/sysutils/SocketClient.h | 13 +++++++++++++ libsysutils/src/SocketClient.cpp | 20 ++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/include/sysutils/SocketClient.h b/include/sysutils/SocketClient.h index 469dd9d08..e7fb17756 100644 --- a/include/sysutils/SocketClient.h +++ b/include/sysutils/SocketClient.h @@ -4,16 +4,29 @@ #include "../../../frameworks/base/include/utils/List.h" #include +#include class SocketClient { int mSocket; pthread_mutex_t mWriteMutex; + /* Peer process ID */ + pid_t mPid; + + /* Peer user ID */ + uid_t mUid; + + /* Peer group ID */ + gid_t mGid; + public: SocketClient(int sock); virtual ~SocketClient() {} int getSocket() { return mSocket; } + pid_t getPid() const { return mPid; } + uid_t getUid() const { return mUid; } + gid_t getGid() const { return mGid; } int sendMsg(int code, const char *msg, bool addErrno); int sendMsg(const char *msg); diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp index e9ae23a90..8e5f1545a 100644 --- a/libsysutils/src/SocketClient.cpp +++ b/libsysutils/src/SocketClient.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -9,9 +10,24 @@ #include -SocketClient::SocketClient(int socket) { - mSocket = socket; +SocketClient::SocketClient(int socket) + : mSocket(socket) + , mPid(-1) + , mUid(-1) + , mGid(-1) +{ pthread_mutex_init(&mWriteMutex, NULL); + + struct ucred creds; + socklen_t szCreds = sizeof(creds); + memset(&creds, 0, szCreds); + + int err = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds); + if (err == 0) { + mPid = creds.pid; + mUid = creds.uid; + mGid = creds.gid; + } } int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {