From 419ce14b6f721834f4afe745d08ede78d55f18cb Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Wed, 3 Jul 2024 03:00:49 +0200 Subject: [PATCH] lib/fs/readlink/: readlinknul(): Add function Signed-off-by: Alejandro Colomar --- lib/Makefile.am | 2 ++ lib/fs/readlink/readlinknul.c | 13 ++++++++++ lib/fs/readlink/readlinknul.h | 46 +++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 lib/fs/readlink/readlinknul.c create mode 100644 lib/fs/readlink/readlinknul.h diff --git a/lib/Makefile.am b/lib/Makefile.am index 89ccc0e35..832c3ab32 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -103,6 +103,8 @@ libshadow_la_SOURCES = \ find_new_sub_gids.c \ find_new_sub_uids.c \ fputsx.c \ + fs/readlink/readlinknul.c \ + fs/readlink/readlinknul.h \ get_pid.c \ getdate.h \ getdate.y \ diff --git a/lib/fs/readlink/readlinknul.c b/lib/fs/readlink/readlinknul.c new file mode 100644 index 000000000..4baea0d01 --- /dev/null +++ b/lib/fs/readlink/readlinknul.c @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2024, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#include + +#include "fs/readlink/readlinknul.h" + +#include + + +extern inline int readlinknul(const char *restrict link, char *restrict buf, + size_t size); diff --git a/lib/fs/readlink/readlinknul.h b/lib/fs/readlink/readlinknul.h new file mode 100644 index 000000000..d813e056d --- /dev/null +++ b/lib/fs/readlink/readlinknul.h @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2024, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#ifndef SHADOW_INCLUDE_LIB_FS_READLINK_READLINKNUL_H_ +#define SHADOW_INCLUDE_LIB_FS_READLINK_READLINKNUL_H_ + + +#include + +#include +#include +#include +#include +#include + +#include "attr.h" + + +ATTR_STRING(1) +inline int readlinknul(const char *restrict link, char *restrict buf, + size_t size); + + +// Similar to readlink(2), but terminate the string. +inline int +readlinknul(const char *restrict link, char *restrict buf, size_t size) +{ + ssize_t len; + + len = readlink(link, buf, size); + if (len == -1) + return -1; + + if (len == size) { + stpcpy(&buf[size-1], ""); + errno = E2BIG; + return -1; + } + + stpcpy(&buf[len], ""); + return len; +} + + +#endif // include guard