pull from samba
[tridge/junkcode.git] / getpwent_replace.c
1 /*
2   a replacement for getpwent() on AIX that enumerates 
3   all user databases, not just /etc/passwd
4
5   Andrew Tridgell tridge@au.ibm.com
6   February 2004
7 */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <pwd.h>
13 #include <usersec.h>
14 #include <sys/types.h>
15
16
17 static struct {
18         char *all_users;
19         char *next;
20 } getpwent_state;
21
22
23 /*
24   free up any resources associated with getpwent() 
25 */
26 void endpwent(void)
27 {
28         if (getpwent_state.all_users) {
29                 free(getpwent_state.all_users);
30         }
31         getpwent_state.all_users = NULL;
32         getpwent_state.next = NULL;
33 }
34
35
36 /*
37   reset the state to the start of the user database
38 */
39 void setpwent(void)
40 {
41         char *s;
42         endpwent();
43         /* getuserattr returns a null separated list of users,
44            with each user being of the form REGISTRY:USERNAME */
45         if (getuserattr("ALL", "users", &s, SEC_CHAR) == 0) {
46                 getpwent_state.all_users = s;
47                 getpwent_state.next = getpwent_state.all_users;
48         }
49         
50 }
51
52 /*
53   get the next user
54 */
55 struct passwd *getpwent(void)
56 {
57         char *user;
58         struct passwd *pwd;
59         if (!getpwent_state.all_users) {
60                 setpwent();
61                 if (!getpwent_state.all_users) {
62                         return NULL;
63                 }
64         }
65         do {
66                 user = getpwent_state.next;
67                 if (!*user) {
68                         endpwent();
69                         return NULL;
70                 }
71                 user = strchr(user, ':');
72                 if (!user) {
73                         endpwent();
74                         return NULL;
75                 }
76                 pwd = getpwnam(user+1);
77                 getpwent_state.next += strlen(getpwent_state.next)+1;
78         } while (!pwd);
79
80         return pwd;
81 }
82
83
84 #if TEST_PROGRAM
85 int main(void)
86 {
87         struct passwd *pwd;
88
89         setpwent();
90
91         while ((pwd = getpwent())) {
92                 printf("%s\n", pwd->pw_name);
93         }
94         
95         endpwent();
96
97         return 0;
98 }
99 #endif