pwd.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <errno.h>
  2. #include <pwd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include "test_helpers.h"
  6. void print(struct passwd *pwd) {
  7. printf("pw_name: %s\n", pwd->pw_name);
  8. printf("pw_password: %s\n", pwd->pw_passwd);
  9. printf("pw_uid: %u\n", pwd->pw_uid);
  10. printf("pw_gid: %u\n", pwd->pw_gid);
  11. printf("pw_gecos: %s\n", pwd->pw_gecos);
  12. printf("pw_dir: %s\n", pwd->pw_dir);
  13. printf("pw_shell: %s\n", pwd->pw_shell);
  14. }
  15. int main(void) {
  16. puts("--- Checking getpwuid ---");
  17. errno = 0;
  18. struct passwd *pwd = getpwuid(0);
  19. if (errno != 0) {
  20. perror("getpwuid");
  21. exit(EXIT_FAILURE);
  22. }
  23. if (pwd != NULL) {
  24. print(pwd);
  25. }
  26. puts("--- Checking getpwnam ---");
  27. errno = 0;
  28. pwd = getpwnam("nobody");
  29. if (errno != 0) {
  30. perror("getpwnam");
  31. exit(EXIT_FAILURE);
  32. }
  33. if (pwd != NULL) {
  34. print(pwd);
  35. }
  36. puts("--- Checking getpwuid_r ---");
  37. struct passwd pwd2;
  38. struct passwd* result;
  39. char* buf = malloc(300);
  40. if (getpwuid_r(0, &pwd2, buf, 100, &result) < 0) {
  41. perror("getpwuid_r");
  42. free(buf);
  43. exit(EXIT_FAILURE);
  44. }
  45. if (result != NULL) {
  46. if (result != &pwd2) {
  47. free(buf);
  48. exit(EXIT_FAILURE);
  49. }
  50. print(&pwd2);
  51. }
  52. puts("--- Checking getpwnam_r ---");
  53. if (getpwnam_r("nobody", &pwd2, buf, 300, &result) < 0) {
  54. perror("getpwuid_r");
  55. free(buf);
  56. exit(EXIT_FAILURE);
  57. }
  58. if (result != NULL) {
  59. if (result != &pwd2) {
  60. free(buf);
  61. exit(EXIT_FAILURE);
  62. }
  63. print(&pwd2);
  64. }
  65. free(buf);
  66. puts("--- Checking getpwuid_r error handling ---");
  67. char buf2[1];
  68. if (getpwuid_r(0, &pwd2, buf2, 1, &result) == 0) {
  69. puts("This shouldn't have succeeded, but it did!");
  70. exit(EXIT_FAILURE);
  71. }
  72. if (errno != ERANGE) {
  73. perror("getpwuid_r");
  74. exit(EXIT_FAILURE);
  75. }
  76. puts("Returned ERANGE because the buffer was too small 👍");
  77. errno = 0;
  78. struct passwd *entry = NULL;
  79. for (int i = 1; entry = getpwent(); ++i) {
  80. int backup = errno;
  81. printf("--- getpwent #%d ---\n", i);
  82. if (backup != 0) {
  83. errno = backup;
  84. perror("getpwent");
  85. exit(EXIT_FAILURE);
  86. }
  87. print(entry);
  88. }
  89. puts("--- getpwent #1 (rewind) ---");
  90. setpwent();
  91. entry = getpwent();
  92. perror("getpwent");
  93. print(entry);
  94. endpwent();
  95. }