From: Iker Pedrosa Date: Wed, 19 Jul 2023 09:02:55 +0000 (+0200) Subject: libmisc: implement `active_sessions_count()` X-Git-Tag: 4.14.0-rc1~8 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=ede0665a5a2aca27eb2c97f6ba756d3164442341;p=thirdparty%2Fshadow.git libmisc: implement `active_sessions_count()` Implement `active_sessions_count()` in `utmp.c` and `logind.c`. Signed-off-by: Iker Pedrosa --- diff --git a/lib/prototypes.h b/lib/prototypes.h index bb3b9391c..a13383410 100644 --- a/lib/prototypes.h +++ b/lib/prototypes.h @@ -511,6 +511,18 @@ extern void record_failure(const char *failent_user, const char *hostname); #endif /* ENABLE_LOGIND */ +/** + * @brief Number of active user sessions + * + * @param[in] name username + * @param[in] limit maximum number of active sessions + * + * @return number of active sessions. + * + */ +extern unsigned long active_sessions_count(const char *name, + unsigned long limit); + /* valid.c */ extern bool valid (const char *, const struct passwd *); diff --git a/libmisc/logind.c b/libmisc/logind.c index ac1b3a141..d4d217ceb 100644 --- a/libmisc/logind.c +++ b/libmisc/logind.c @@ -34,3 +34,18 @@ done: free (session); return ret; } + +unsigned long active_sessions_count(const char *name, unsigned long unused) +{ + struct passwd *pw; + unsigned long count = 0; + + pw = prefix_getpwnam(name); + if (pw == NULL) { + return 0; + } + + count = sd_uid_get_sessions(pw->pw_uid, 0, NULL); + + return count; +} diff --git a/libmisc/utmp.c b/libmisc/utmp.c index 0a86b18e3..e5e79cffc 100644 --- a/libmisc/utmp.c +++ b/libmisc/utmp.c @@ -395,3 +395,30 @@ void record_failure(const char *failent_user, free (failent); } } + +unsigned long active_sessions_count(const char *name, unsigned long limit) +{ + struct utmp *ut; + unsigned long count = 0; + + setutent (); + while ((ut = getutent ())) + { + if (USER_PROCESS != ut->ut_type) { + continue; + } + if ('\0' == ut->ut_user[0]) { + continue; + } + if (strncmp (name, ut->ut_user, sizeof (ut->ut_user)) != 0) { + continue; + } + count++; + if (count > limit) { + break; + } + } + endutent (); + + return count; +}