Code

frontend: Get the username of the remote peer from a UNIX socket.
[sysdb.git] / src / frontend / connection.c
index e384bafa98297a7cf46c9283dee7b70a9c484dab..b27b3dd28bfbfd0324941d1861bc2bdd5d60a8ca 100644 (file)
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#ifdef HAVE_CONFIG_H
+#      include "config.h"
+#endif
+
 #include "sysdb.h"
 #include "core/object.h"
 #include "core/plugin.h"
 #include <stdlib.h>
 #include <string.h>
 
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/param.h>
+
+#ifdef HAVE_UCRED_H
+#      include <ucred.h>
+#endif
+#ifdef HAVE_SYS_UCRED_H
+#      include <sys/ucred.h>
+#endif
+
+#include <pwd.h>
+
 #include <pthread.h>
 
 /*
@@ -59,6 +76,36 @@ static bool          conn_ctx_key_initialized = 0;
 #define CONN_FD_PREFIX "conn#"
 #define CONN_FD_PLACEHOLDER "XXXXXXX"
 
+/* XXX: only supports UNIX sockets so far */
+static char *
+peer(int sockfd)
+{
+       uid_t uid;
+
+       struct passwd pw_entry;
+       struct passwd *result = NULL;
+       char buf[1024];
+
+#ifdef SO_PEERCRED
+       struct ucred cred;
+       socklen_t len = sizeof(cred);
+
+       if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cred, &len)
+                       || (len != sizeof(cred)))
+               return NULL;
+       uid = cred.uid;
+#else /* SO_PEERCRED */
+       errno = ENOSYS;
+       return NULL;
+#endif
+
+       memset(&pw_entry, 0, sizeof(pw_entry));
+       if (getpwuid_r(uid, &pw_entry, buf, sizeof(buf), &result)
+                       || (! result))
+               return NULL;
+       return strdup(result->pw_name);
+} /* peer */
+
 static int
 connection_init(sdb_object_t *obj, va_list ap)
 {
@@ -111,6 +158,16 @@ connection_init(sdb_object_t *obj, va_list ap)
                return -1;
        }
 
+       conn->username = peer(conn->fd);
+       if (! conn->username) {
+               char buf[1024];
+               sdb_log(SDB_LOG_ERR, "frontend: Failed to retrieve peer for "
+                               "connection conn#%i: %s", conn->fd,
+                               sdb_strerror(errno, buf, sizeof(buf)));
+               return -1;
+       }
+       conn->ready = 0;
+
        sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
                        conn->fd);