user_group_parse.c (1576B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include "./user_group_parse.h"
- #include <assert.h>
- #include <errno.h>
- #include <grp.h> // getgrnam
- #include <pwd.h> // getpwnam
- #include <stdio.h> // fprintf
- #include <stdlib.h> // strtoul
- #include <string.h> // strerror
- int
- parse_user(char *str, uid_t *user)
- {
- if(str == NULL) return -1;
- if(str[0] == 0) return 0;
- assert(errno == 0);
- char *endptr = NULL;
- unsigned long id = strtoul(str, &endptr, 0);
- if(errno == 0 && endptr != NULL && *endptr == '\0')
- {
- *user = (uid_t)id;
- return 0;
- }
- errno = 0;
- struct passwd *pw = getpwnam(str);
- if(pw == NULL)
- {
- const char *e = strerror(errno);
- if(errno == 0) e = "Entry Not Found";
- fprintf(stderr, "%s: error: Failed to get entry for username '%s': %s\n", argv0, str, e);
- return -1;
- }
- *user = pw->pw_uid;
- return 0;
- }
- int
- parse_group(char *str, gid_t *group)
- {
- if(str == NULL) return -1;
- if(str[0] == 0) return 0;
- assert(errno == 0);
- char *endptr = NULL;
- unsigned int id = strtoul(str, &endptr, 0);
- if(errno == 0 && endptr != NULL && *endptr == '\0')
- {
- *group = id;
- return 0;
- }
- errno = 0;
- struct group *gr = getgrnam(str);
- if(gr == NULL)
- {
- const char *e = strerror(errno);
- if(errno == 0) e = "Entry Not Found";
- fprintf(stderr, "%s: error: Failed to get entry for group '%s': %s\n", argv0, str, e);
- return -1;
- }
- *group = gr->gr_gid;
- return 0;
- }