1
0

db.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #include <stdlib.h>
  2. #include <errno.h>
  3. #include <sys/types.h>
  4. #include <pwd.h>
  5. #include <grp.h>
  6. #include <unistd.h>
  7. #include "lub/db.h"
  8. struct passwd *lub_db_getpwnam(const char *name)
  9. {
  10. size_t size;
  11. char *buf;
  12. struct passwd *pwbuf;
  13. struct passwd *pw = NULL;
  14. int res = 0;
  15. size = sysconf(_SC_GETPW_R_SIZE_MAX);
  16. pwbuf = malloc(sizeof(*pwbuf) + size);
  17. if (!pwbuf)
  18. return NULL;
  19. buf = (char *)pwbuf + sizeof(*pwbuf);
  20. res = getpwnam_r(name, pwbuf, buf, size, &pw);
  21. if (res || !pw) {
  22. free(pwbuf);
  23. if (res != 0)
  24. errno = res;
  25. else
  26. errno = ENOENT;
  27. return NULL;
  28. }
  29. return pw;
  30. }
  31. struct passwd *lub_db_getpwuid(uid_t uid)
  32. {
  33. size_t size;
  34. char *buf;
  35. struct passwd *pwbuf;
  36. struct passwd *pw = NULL;
  37. int res = 0;
  38. size = sysconf(_SC_GETPW_R_SIZE_MAX);
  39. pwbuf = malloc(sizeof(*pwbuf) + size);
  40. if (!pwbuf)
  41. return NULL;
  42. buf = (char *)pwbuf + sizeof(*pwbuf);
  43. res = getpwuid_r(uid, pwbuf, buf, size, &pw);
  44. if (NULL == pw) {
  45. free(pwbuf);
  46. if (res != 0)
  47. errno = res;
  48. else
  49. errno = ENOENT;
  50. return NULL;
  51. }
  52. return pw;
  53. }
  54. struct group *lub_db_getgrnam(const char *name)
  55. {
  56. size_t size;
  57. char *buf;
  58. struct group *grbuf;
  59. struct group *gr = NULL;
  60. int res = 0;
  61. size = sysconf(_SC_GETGR_R_SIZE_MAX);
  62. grbuf = malloc(sizeof(*grbuf) + size);
  63. if (!grbuf)
  64. return NULL;
  65. buf = (char *)grbuf + sizeof(*grbuf);
  66. res = getgrnam_r(name, grbuf, buf, size, &gr);
  67. if (NULL == gr) {
  68. free(grbuf);
  69. if (res != 0)
  70. errno = res;
  71. else
  72. errno = ENOENT;
  73. return NULL;
  74. }
  75. return gr;
  76. }
  77. struct group *lub_db_getgrgid(gid_t gid)
  78. {
  79. size_t size;
  80. char *buf;
  81. struct group *grbuf;
  82. struct group *gr = NULL;
  83. int res = 0;
  84. size = sysconf(_SC_GETGR_R_SIZE_MAX);
  85. grbuf = malloc(sizeof(struct group) + size);
  86. if (!grbuf)
  87. return NULL;
  88. buf = (char *)grbuf + sizeof(struct group);
  89. res = getgrgid_r(gid, grbuf, buf, size, &gr);
  90. if (!gr) {
  91. free(grbuf);
  92. if (res != 0)
  93. errno = res;
  94. else
  95. errno = ENOENT;
  96. return NULL;
  97. }
  98. return gr;
  99. }