getgrent.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /*
  2. * getgrent - get entry form group file
  3. *
  4. * Author: Patrick van Kleef
  5. */
  6. /* $Id$ */
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <grp.h>
  10. #define O_RDONLY 0
  11. int open(const char *path, int flags);
  12. #if defined(__BSD4_2)
  13. typedef int off_t; /* see lseek(2) */
  14. #else
  15. typedef long off_t;
  16. #endif
  17. off_t _lseek(int d, off_t offset, int whence);
  18. int _read(int d, char *buf, int nbytes);
  19. int _close(int d);
  20. #define RBUFSIZE 1024
  21. static char _gr_file[] = "/etc/group";
  22. static char _grbuf[256];
  23. static char _buffer[RBUFSIZE];
  24. static char *_pnt;
  25. static char *_buf;
  26. static int _gfd = -1;
  27. static int _bufcnt;
  28. static struct group grp;
  29. int
  30. setgrent(void)
  31. {
  32. if (_gfd >= 0)
  33. _lseek(_gfd, 0L, 0);
  34. else
  35. _gfd = open(_gr_file, O_RDONLY);
  36. _bufcnt = 0;
  37. return _gfd;
  38. }
  39. void
  40. endgrent(void)
  41. {
  42. if (_gfd >= 0)
  43. _close(_gfd);
  44. _gfd = -1;
  45. _bufcnt = 0;
  46. }
  47. static int
  48. getline(void)
  49. {
  50. if (_gfd < 0 && setgrent() < 0)
  51. return 0;
  52. _buf = _grbuf;
  53. do {
  54. if (--_bufcnt <= 0){
  55. if ((_bufcnt = _read(_gfd, _buffer, RBUFSIZE)) <= 0)
  56. return 0;
  57. else
  58. _pnt = _buffer;
  59. }
  60. *_buf++ = *_pnt++;
  61. } while (*_pnt != '\n');
  62. _pnt++;
  63. _bufcnt--;
  64. *_buf = 0;
  65. _buf = _grbuf;
  66. return 1;
  67. }
  68. static void
  69. skip_period(void)
  70. {
  71. while (*_buf && *_buf != ':')
  72. _buf++;
  73. *_buf++ = '\0';
  74. }
  75. struct group *
  76. getgrent(void)
  77. {
  78. if (getline() == 0)
  79. return 0;
  80. grp.gr_name = _buf;
  81. skip_period();
  82. grp.gr_passwd = _buf;
  83. skip_period();
  84. grp.gr_gid = atoi(_buf);
  85. skip_period();
  86. return &grp;
  87. }
  88. struct group *
  89. getgrnam(const char *name)
  90. {
  91. struct group *g;
  92. setgrent();
  93. while ((g = getgrent()) != 0)
  94. if (!strcmp(g -> gr_name, name))
  95. break;
  96. endgrent();
  97. if (g != 0)
  98. return g;
  99. else
  100. return 0;
  101. }
  102. struct group *
  103. getgrgid(int gid)
  104. {
  105. struct group *g;
  106. setgrent();
  107. while ((g = getgrent()) != 0)
  108. if (g -> gr_gid == gid)
  109. break;
  110. endgrent();
  111. if (g != 0)
  112. return g;
  113. else
  114. return 0;
  115. }