[PATCHv2] query logind/elogind for number of users

"Thorsten Kukuk" <[email protected]> ("kukuk") Thu, 9 Mar 2023 12:01:57 +0100
Newsgroups gmane.linux.procps.devel
Message-ID <[email protected]>
--ReaqsoxgOBHFXBhH
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: 8bit


Hi,

a new patch which uses utmp as fallback and prints '?' in error case.

  Thorsten

-- 
Thorsten Kukuk, Distinguished Engineer, Senior Architect, Future Technologies
SUSE Software Solutions Germany GmbH, Frankenstraße 146, 90461 Nuernberg, Germany
Managing Director: Ivo Totev, Andrew Myers, Andrew McDonald, Martje Boudien Moerman
(HRB 36809, AG Nürnberg)

--ReaqsoxgOBHFXBhH
Content-Type: text/x-patch; charset=us-ascii
Content-Disposition: attachment; filename="0001-library-use-sd_get_sessions-instead-of-utmp.patch"

From 931e5736cb8ad356e247febb3385f04a1b1a6fe4 Mon Sep 17 00:00:00 2001
From: Thorsten Kukuk <[email protected]>
Date: Tue, 7 Mar 2023 10:30:50 +0100
Subject: [PATCH 1/2] library: use sd_get_sessions() instead of utmp

The utmp format of glibc is not Y2038 safe, not even on 64bit systems.
Query logind/elogind for the number of users if we use libsystemd.

Signed-off-by: Thorsten Kukuk <[email protected]>
---
 library/uptime.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)

diff --git a/library/uptime.c b/library/uptime.c
index 16f1b05d..bb9344a2 100644
--- a/library/uptime.c
+++ b/library/uptime.c
@@ -31,6 +31,12 @@
 #include <time.h>
 #include <unistd.h>
 #include <utmp.h>
+#ifdef WITH_SYSTEMD
+#include <systemd/sd-login.h>
+#endif
+#ifdef WITH_ELOGIND
+#include <elogind/sd-login.h>
+#endif
 
 #include "misc.h"
 #include "procps-private.h"
@@ -45,6 +51,13 @@ static int count_users(void)
     int numuser = 0;
     struct utmp *ut;
 
+#if defined(WITH_SYSTEMD) || defined(WITH_ELOGIND)
+    numuser = sd_get_sessions(NULL);
+
+    if (numuser >= 0 || numuser != ENOENT)
+      return numuser;
+#endif
+
     setutent();
     while ((ut = getutent())) {
     if ((ut->ut_type == USER_PROCESS) && (ut->ut_name[0] != '\0'))
@@ -136,8 +149,13 @@ PROCPS_EXPORT char *procps_uptime_sprint(void)
     users = count_users();
     procps_loadavg(&av1, &av5, &av15);
 
-    pos += sprintf(upbuf + pos, "%2d %s,  load average: %.2f, %.2f, %.2f",
-        users, users > 1 ? "users" : "user",
+    if (users < 0)
+      pos += sprintf(upbuf + pos, " ? ");
+    else
+      pos += sprintf(upbuf + pos, "%2d ", users);
+
+    pos += sprintf(upbuf + pos, "%s,  load average: %.2f, %.2f, %.2f",
+        users > 1 ? "users" : "user",
         av1, av5, av15);
 
     return upbuf;
@@ -248,4 +266,3 @@ PROCPS_EXPORT char *procps_uptime_sprint_short(void)
     }
     return shortbuf;
 }
-
-- 
2.39.2


--ReaqsoxgOBHFXBhH--