/*1* SPDX-License-Identifier: ISC2*3* Copyright (c) 2013-2015 Todd C. Miller <[email protected]>4*5* Permission to use, copy, modify, and distribute this software for any6* purpose with or without fee is hereby granted, provided that the above7* copyright notice and this permission notice appear in all copies.8*9* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES10* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF11* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR12* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES13* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN14* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF15* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.16*/1718#include <config.h>1920#include <stdlib.h>21#include <grp.h>2223#include <sudo_compat.h>24#include <sudo_debug.h>25#include <sudo_fatal.h>26#include <sudo_gettext.h>27#include <sudo_util.h>2829/*30* Parse a comma-separated list of gids into an allocated array of GETGROUPS_T.31* If a pointer to the base gid is specified, it is stored as the first element32* in the array.33* Returns the number of gids in the allocated array.34*/35int36sudo_parse_gids_v1(const char *gidstr, const gid_t *basegid, GETGROUPS_T **gidsp)37{38int ngids = 0;39GETGROUPS_T *gids;40const char *cp = gidstr;41const char *errstr;42char *ep;43debug_decl(sudo_parse_gids, SUDO_DEBUG_UTIL);4445/* Count groups. */46if (*cp != '\0') {47ngids++;48do {49if (*cp++ == ',')50ngids++;51} while (*cp != '\0');52}53/* Base gid is optional. */54if (basegid != NULL)55ngids++;56/* Allocate and fill in array. */57if (ngids != 0) {58gids = reallocarray(NULL, (size_t)ngids, sizeof(GETGROUPS_T));59if (gids == NULL) {60sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));61debug_return_int(-1);62}63ngids = 0;64if (basegid != NULL)65gids[ngids++] = *basegid;66cp = gidstr;67do {68gids[ngids] = (GETGROUPS_T) sudo_strtoidx(cp, ",", &ep, &errstr);69if (errstr != NULL) {70sudo_warnx(U_("%s: %s"), cp, U_(errstr));71free(gids);72debug_return_int(-1);73}74if (basegid == NULL || gids[ngids] != *basegid)75ngids++;76cp = ep + 1;77} while (*ep != '\0');78*gidsp = gids;79}80debug_return_int(ngids);81}828384