From 0ebba73cb8d74d18d6af87bbed99e91bac6a4eac Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Mon, 20 Aug 2018 16:11:17 +0200 Subject: [PATCH] net/SocketDescriptor: add method GetPeerCredentials() --- src/net/SocketDescriptor.cxx | 26 ++++++++++++++++++++++++++ src/net/SocketDescriptor.hxx | 14 ++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/net/SocketDescriptor.cxx b/src/net/SocketDescriptor.cxx index 395ed5401..a5f752342 100644 --- a/src/net/SocketDescriptor.cxx +++ b/src/net/SocketDescriptor.cxx @@ -220,6 +220,32 @@ SocketDescriptor::GetError() : errno; } +size_t +SocketDescriptor::GetOption(int level, int name, + void *value, size_t size) const +{ + assert(IsDefined()); + + socklen_t size2 = size; + return getsockopt(fd, level, name, (char *)value, &size2) == 0 + ? size2 + : 0; +} + +#ifdef HAVE_STRUCT_UCRED + +struct ucred +SocketDescriptor::GetPeerCredentials() const noexcept +{ + struct ucred cred; + if (GetOption(SOL_SOCKET, SO_PEERCRED, + &cred, sizeof(cred)) < sizeof(cred)) + cred.pid = -1; + return cred; +} + +#endif + #ifdef _WIN32 bool diff --git a/src/net/SocketDescriptor.hxx b/src/net/SocketDescriptor.hxx index 33bde8c79..8122b9f9e 100644 --- a/src/net/SocketDescriptor.hxx +++ b/src/net/SocketDescriptor.hxx @@ -150,6 +150,20 @@ public: int GetError(); + /** + * @return the value size or 0 on error + */ + size_t GetOption(int level, int name, void *value, size_t size) const; + +#ifdef HAVE_STRUCT_UCRED + /** + * Receive peer credentials (SO_PEERCRED). On error, the pid + * is -1. + */ + gcc_pure + struct ucred GetPeerCredentials() const noexcept; +#endif + bool SetOption(int level, int name, const void *value, size_t size); bool SetBoolOption(int level, int name, bool _value) {