From 927f6ea2211d20b521bf35136c55c0147ce48a4f Mon Sep 17 00:00:00 2001 From: M4x1m3 Date: Fri, 9 Jul 2021 14:32:12 +0200 Subject: LibC: Add putgrent --- Userland/Libraries/LibC/grp.cpp | 43 +++++++++++++++++++++++++++++++++++++++++ Userland/Libraries/LibC/grp.h | 2 ++ 2 files changed, 45 insertions(+) (limited to 'Userland/Libraries/LibC') diff --git a/Userland/Libraries/LibC/grp.cpp b/Userland/Libraries/LibC/grp.cpp index a3032b569d..6c22723407 100644 --- a/Userland/Libraries/LibC/grp.cpp +++ b/Userland/Libraries/LibC/grp.cpp @@ -1,11 +1,13 @@ /* * Copyright (c) 2018-2020, Andreas Kling + * Copyright (c) 2021, Maxime Friess * * SPDX-License-Identifier: BSD-2-Clause */ #include #include +#include #include #include #include @@ -159,4 +161,45 @@ int initgroups(const char* user, gid_t extra_gid) gids[count++] = extra_gid; return setgroups(count, gids); } + +int putgrent(const struct group* group, FILE* stream) +{ + if (!group || !stream || !group->gr_name || !group->gr_passwd) { + errno = EINVAL; + return -1; + } + + auto is_valid_field = [](const char* str) { + return str && !strpbrk(str, ":\n"); + }; + + if (!is_valid_field(group->gr_name) || !is_valid_field(group->gr_passwd)) { + errno = EINVAL; + return -1; + } + + int nwritten = fprintf(stream, "%s:%s:%u:", group->gr_name, group->gr_passwd, group->gr_gid); + if (!nwritten || nwritten < 0) { + errno = ferror(stream); + return -1; + } + + if (group->gr_mem) { + for (size_t i = 0; group->gr_mem[i] != nullptr; i++) { + nwritten = fprintf(stream, i == 0 ? "%s" : ",%s", group->gr_mem[i]); + if (!nwritten || nwritten < 0) { + errno = ferror(stream); + return -1; + } + } + } + + nwritten = fprintf(stream, "\n"); + if (!nwritten || nwritten < 0) { + errno = ferror(stream); + return -1; + } + + return 0; +} } diff --git a/Userland/Libraries/LibC/grp.h b/Userland/Libraries/LibC/grp.h index c9cefee47a..c2b3c89cbc 100644 --- a/Userland/Libraries/LibC/grp.h +++ b/Userland/Libraries/LibC/grp.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2018-2020, Andreas Kling + * Copyright (c) 2021, Maxime Friess * * SPDX-License-Identifier: BSD-2-Clause */ @@ -23,6 +24,7 @@ void setgrent(); void endgrent(); struct group* getgrnam(const char* name); struct group* getgrgid(gid_t); +int putgrent(const struct group*, FILE*); int initgroups(const char* user, gid_t); -- cgit v1.2.3