logo

utils-std

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

user_group_parse.c (1576B)


  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 <assert.h>
  7. #include <errno.h>
  8. #include <grp.h> // getgrnam
  9. #include <pwd.h> // getpwnam
  10. #include <stdio.h> // fprintf
  11. #include <stdlib.h> // strtoul
  12. #include <string.h> // strerror
  13. int
  14. parse_user(char *str, uid_t *user)
  15. {
  16. if(str == NULL) return -1;
  17. if(str[0] == 0) return 0;
  18. assert(errno == 0);
  19. char *endptr = NULL;
  20. unsigned long id = strtoul(str, &endptr, 0);
  21. if(errno == 0 && endptr != NULL && *endptr == '\0')
  22. {
  23. *user = (uid_t)id;
  24. return 0;
  25. }
  26. errno = 0;
  27. struct passwd *pw = getpwnam(str);
  28. if(pw == NULL)
  29. {
  30. const char *e = strerror(errno);
  31. if(errno == 0) e = "Entry Not Found";
  32. fprintf(stderr, "%s: error: Failed to get entry for username '%s': %s\n", argv0, str, e);
  33. return -1;
  34. }
  35. *user = pw->pw_uid;
  36. return 0;
  37. }
  38. int
  39. parse_group(char *str, gid_t *group)
  40. {
  41. if(str == NULL) return -1;
  42. if(str[0] == 0) return 0;
  43. assert(errno == 0);
  44. char *endptr = NULL;
  45. unsigned int id = strtoul(str, &endptr, 0);
  46. if(errno == 0 && endptr != NULL && *endptr == '\0')
  47. {
  48. *group = id;
  49. return 0;
  50. }
  51. errno = 0;
  52. struct group *gr = getgrnam(str);
  53. if(gr == NULL)
  54. {
  55. const char *e = strerror(errno);
  56. if(errno == 0) e = "Entry Not Found";
  57. fprintf(stderr, "%s: error: Failed to get entry for group '%s': %s\n", argv0, str, e);
  58. return -1;
  59. }
  60. *group = gr->gr_gid;
  61. return 0;
  62. }