logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

user_group_parse.c (1514B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include "./user_group_parse.h"
  6. #include <errno.h>
  7. #include <grp.h> // getgrnam
  8. #include <pwd.h> // getpwnam
  9. #include <stdio.h> // fprintf
  10. #include <stdlib.h> // strtoul
  11. #include <string.h> // strerror
  12. int
  13. parse_user(char *str, uid_t *user)
  14. {
  15. if(str == NULL) return -1;
  16. if(str[0] == 0) return 0;
  17. char *endptr = NULL;
  18. unsigned long id = strtoul(str, &endptr, 0);
  19. if(errno == 0 && endptr != NULL && *endptr == '\0')
  20. {
  21. *user = (uid_t)id;
  22. return 0;
  23. }
  24. errno = 0;
  25. struct passwd *pw = getpwnam(str);
  26. if(pw == NULL)
  27. {
  28. const char *e = strerror(errno);
  29. if(errno == 0) e = "Entry Not Found";
  30. fprintf(stderr, "%s: error: Failed to get entry for username '%s': %s\n", argv0, str, e);
  31. return -1;
  32. }
  33. *user = pw->pw_uid;
  34. return 0;
  35. }
  36. int
  37. parse_group(char *str, gid_t *group)
  38. {
  39. if(str == NULL) return -1;
  40. if(str[0] == 0) return 0;
  41. char *endptr = NULL;
  42. unsigned int id = strtoul(str, &endptr, 0);
  43. if(errno == 0 && endptr != NULL && *endptr == '\0')
  44. {
  45. *group = id;
  46. return 0;
  47. }
  48. errno = 0;
  49. struct group *gr = getgrnam(str);
  50. if(gr == NULL)
  51. {
  52. const char *e = strerror(errno);
  53. if(errno == 0) e = "Entry Not Found";
  54. fprintf(stderr, "%s: error: Failed to get entry for group '%s': %s\n", argv0, str, e);
  55. return -1;
  56. }
  57. *group = gr->gr_gid;
  58. return 0;
  59. }