diff --git a/lib/Makefile.am b/lib/Makefile.am index d709345986..8a967ca9c8 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -115,6 +115,8 @@ libshadow_la_SOURCES = \ lockpw.c \ loginprompt.c \ mail.c \ + memory/strnlen/strnlen.c \ + memory/strnlen/strnlen.h \ motd.c \ myname.c \ nss.c \ diff --git a/lib/memory/strnlen/strnlen.c b/lib/memory/strnlen/strnlen.c new file mode 100644 index 0000000000..d8f60c3c96 --- /dev/null +++ b/lib/memory/strnlen/strnlen.c @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: 2025-2026, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#include "config.h" + +#include "memory/strnlen/strnlen.h" diff --git a/lib/memory/strnlen/strnlen.h b/lib/memory/strnlen/strnlen.h new file mode 100644 index 0000000000..4d16c8a604 --- /dev/null +++ b/lib/memory/strnlen/strnlen.h @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2025-2026, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#ifndef SHADOW_INCLUDE_LIB_MEMORY_STRNLEN_STRNLEN_H_ +#define SHADOW_INCLUDE_LIB_MEMORY_STRNLEN_STRNLEN_H_ + + +#include "config.h" + +#include + +#include "sizeof.h" + + +// strnlen_a - nonstring length array +#define strnlen_a(strn) strnlen(strn, countof(strn)) + + +#endif // include guard diff --git a/lib/string/README b/lib/string/README index 70274d71de..21818078cb 100644 --- a/lib/string/README +++ b/lib/string/README @@ -288,6 +288,11 @@ strsep/ - String separation Variant of strsep2ls() that allocates the array of strings. (But the strings themselves are not duplicated.) +strnlen/ - String length + + strnlen_a() + Like strnlen(3), but take an array. + strftime.h strftime_a() Like strftime(3), but takes an array. diff --git a/lib/utmp.c b/lib/utmp.c index 62002768e6..439c1b7293 100644 --- a/lib/utmp.c +++ b/lib/utmp.c @@ -30,6 +30,7 @@ #include "alloc/malloc.h" #include "attr.h" #include "io/syslog.h" +#include "memory/strnlen/strnlen.h" #include "sizeof.h" #include "string/strchr/strnul.h" #include "string/strcmp/streq.h" @@ -301,8 +302,7 @@ prepare_utmp(const char *name, const char *line, const char *host, strncpy_a(utent->ut_host, hostname); #endif #if defined(HAVE_STRUCT_UTMPX_UT_SYSLEN) - utent->ut_syslen = MIN(strlen(hostname), - sizeof(utent->ut_host)); + utent->ut_syslen = strnlen_a(utent->ut_host); #endif #if defined(HAVE_STRUCT_UTMPX_UT_ADDR) || defined(HAVE_STRUCT_UTMPX_UT_ADDR_V6) if (getaddrinfo (hostname, NULL, NULL, &info) == 0) {