libmisc: implement get_session_host()

Implement `get_session_host()` in `utmp.c` and `logind.c`.

Signed-off-by: Iker Pedrosa <ipedrosa@redhat.com>
This commit is contained in:
Iker Pedrosa
2023-07-18 15:56:46 +02:00
committed by Serge Hallyn
parent fb35ad15ae
commit f40bdfa66a
4 changed files with 76 additions and 2 deletions

View File

@@ -472,7 +472,19 @@ extern int set_filesize_limit (int blocks);
/* user_busy.c */
extern int user_busy (const char *name, uid_t uid);
/* utmp.c */
/*
* Session management: utmp.c or logind.c
*/
/**
* @brief Get host for the current session
*
* @param[out] out Host name
*
* @return 0 or a positive integer if the host was obtained properly,
* another value on error.
*/
extern int get_session_host (char **out);
extern /*@null@*/struct utmp *get_current_utmp (void);
extern struct utmp *prepare_utmp (const char *name,
const char *line,

View File

@@ -94,4 +94,4 @@ endif
if ENABLE_LASTLOG
libmisc_la_SOURCES += log.c
endif
endif

36
libmisc/logind.c Normal file
View File

@@ -0,0 +1,36 @@
/*
* SPDX-FileCopyrightText: 2023, Iker Pedrosa <ipedrosa@redhat.com>
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <config.h>
#ident "$Id$"
#include "defines.h"
#include "prototypes.h"
#include <systemd/sd-login.h>
int get_session_host (char **out)
{
char *host = NULL;
char *session = NULL;
int ret;
ret = sd_pid_get_session (getpid(), &session);
if (ret < 0) {
return ret;
}
ret = sd_session_get_remote_host (session, &host);
if (ret < 0) {
goto done;
}
*out = host;
done:
free (session);
return ret;
}

View File

@@ -101,6 +101,32 @@ static bool is_my_tty (const char tty[UT_LINESIZE])
return ret;
}
int get_session_host (char **out)
{
char *hostname = NULL;
struct utmp *ut = NULL;
int ret = 0;
ut = get_current_utmp();
#ifdef HAVE_STRUCT_UTMP_UT_HOST
if ((ut != NULL) && (ut->ut_host[0] != '\0')) {
hostname = XMALLOC(sizeof(ut->ut_host) + 1, char);
strncpy (hostname, ut->ut_host, sizeof (ut->ut_host));
hostname[sizeof (ut->ut_host)] = '\0';
*out = hostname;
free (ut);
} else {
*out = NULL;
ret = -2;
}
#else
*out = NULL;
ret = -2;
#endif /* HAVE_STRUCT_UTMP_UT_HOST */
return ret;
}
#ifndef USE_PAM
/*