libpwdgrp: code shrink
[oweals/busybox.git] / libpwdgrp / pwd_grp.c
1 /* vi: set sw=4 ts=4: */
2 /* Copyright (C) 2014 Tito Ragusa <farmatito@tiscali.it>
3  *
4  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
5  */
6 /* This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY!!
8  *
9  * Rewrite of some parts. Main differences are:
10  *
11  * 1) the buffer for getpwuid, getgrgid, getpwnam, getgrnam is dynamically
12  *    allocated and reused by later calls.
13  *    If ENABLE_FEATURE_CLEAN_UP is set the buffers are freed at program
14  *    exit using the atexit function to make valgrind happy.
15  * 2) the passwd/group files:
16  *      a) must contain the expected number of fields (as per count of field
17  *         delimeters ":") or we will complain with a error message.
18  *      b) leading or trailing whitespace in fields is stripped.
19  *      c) some fields are not allowed to be empty (e.g. username, uid/gid,
20  *         homedir, shell) and in this case NULL is returned and errno is
21  *         set to EINVAL. This behaviour could be easily changed by
22  *         modifying PW_DEF, GR_DEF, SP_DEF strings (uppercase
23  *         makes a field mandatory).
24  *      d) the string representing uid/gid must be convertible by strtoXX
25  *         functions, or errno is set to EINVAL.
26  *      e) leading or trailing whitespace in group member names are stripped.
27  * 3) the internal function for getgrouplist uses dynamically allocated buffer.
28  * 4) at the moment only the functions really used by busybox code are
29  *    implemented, if you need a particular missing function it should be
30  *    easy to write it by using the internal common code.
31  */
32
33 #include "libbb.h"
34
35 struct const_passdb {
36         const char *filename;
37         const char def[7 + 2*ENABLE_USE_BB_SHADOW];
38         const uint8_t off[7 + 2*ENABLE_USE_BB_SHADOW];
39         uint8_t numfields;
40         uint8_t size_of;
41 };
42 struct passdb {
43         const char *filename;
44         const char def[7 + 2*ENABLE_USE_BB_SHADOW];
45         const uint8_t off[7 + 2*ENABLE_USE_BB_SHADOW];
46         uint8_t numfields;
47         uint8_t size_of;
48         FILE *fp;
49         char *malloced;
50 };
51 /* Note: for shadow db, def[] will not contain terminating NUL,
52  * but convert_to_struct() logic detects def[] end by "less than SP?",
53  * not by "is it NUL?" condition; and off[0] happens to be zero
54  * for every db anyway, so there _is_ in fact a terminating NUL there.
55  */
56
57 /* S = string not empty, s = string maybe empty,
58  * I = uid,gid, l = long maybe empty, m = members,
59  * r = reserved
60  */
61 #define PW_DEF "SsIIsSS"
62 #define GR_DEF "SsIm"
63 #define SP_DEF "Ssllllllr"
64
65 static const struct const_passdb const_pw_db = {
66         _PATH_PASSWD, PW_DEF,
67         {
68                 offsetof(struct passwd, pw_name),       /* 0 S */
69                 offsetof(struct passwd, pw_passwd),     /* 1 s */
70                 offsetof(struct passwd, pw_uid),        /* 2 I */
71                 offsetof(struct passwd, pw_gid),        /* 3 I */
72                 offsetof(struct passwd, pw_gecos),      /* 4 s */
73                 offsetof(struct passwd, pw_dir),        /* 5 S */
74                 offsetof(struct passwd, pw_shell)       /* 6 S */
75         },
76         sizeof(PW_DEF)-1, sizeof(struct passwd)
77 };
78 static const struct const_passdb const_gr_db = {
79         _PATH_GROUP, GR_DEF,
80         {
81                 offsetof(struct group, gr_name),        /* 0 S */
82                 offsetof(struct group, gr_passwd),      /* 1 s */
83                 offsetof(struct group, gr_gid),         /* 2 I */
84                 offsetof(struct group, gr_mem)          /* 3 m (char **) */
85         },
86         sizeof(GR_DEF)-1, sizeof(struct group)
87 };
88 #if ENABLE_USE_BB_SHADOW
89 static const struct const_passdb const_sp_db = {
90         _PATH_SHADOW, SP_DEF,
91         {
92                 offsetof(struct spwd, sp_namp),         /* 0 S Login name */
93                 offsetof(struct spwd, sp_pwdp),         /* 1 s Encrypted password */
94                 offsetof(struct spwd, sp_lstchg),       /* 2 l */
95                 offsetof(struct spwd, sp_min),          /* 3 l */
96                 offsetof(struct spwd, sp_max),          /* 4 l */
97                 offsetof(struct spwd, sp_warn),         /* 5 l */
98                 offsetof(struct spwd, sp_inact),        /* 6 l */
99                 offsetof(struct spwd, sp_expire),       /* 7 l */
100                 offsetof(struct spwd, sp_flag)          /* 8 r Reserved */
101         },
102         sizeof(SP_DEF)-1, sizeof(struct spwd)
103 };
104 #endif
105
106 /* We avoid having big global data. */
107 struct statics {
108         /* It's ok to use same buffer (db[0].malloced) for getpwuid and getpwnam.
109          * Manpage says:
110          * "The return value may point to a static area, and may be overwritten
111          * by subsequent calls to getpwent(), getpwnam(), or getpwuid()."
112          */
113         struct passdb db[2 + ENABLE_USE_BB_SHADOW];
114         char *tokenize_end;
115         unsigned string_size;
116 };
117
118 static struct statics *ptr_to_statics;
119 #define S     (*ptr_to_statics)
120 #define has_S (ptr_to_statics)
121
122 #if ENABLE_FEATURE_CLEAN_UP
123 static void free_static(void)
124 {
125         free(S.db[0].malloced);
126         free(S.db[1].malloced);
127 # if ENABLE_USE_BB_SHADOW
128         free(S.db[2].malloced);
129 # endif
130         free(ptr_to_statics);
131 }
132 #endif
133
134 static struct statics *get_S(void)
135 {
136         if (!ptr_to_statics) {
137                 ptr_to_statics = xzalloc(sizeof(S));
138                 memcpy(&S.db[0], &const_pw_db, sizeof(const_pw_db));
139                 memcpy(&S.db[1], &const_gr_db, sizeof(const_gr_db));
140 #if ENABLE_USE_BB_SHADOW
141                 memcpy(&S.db[2], &const_sp_db, sizeof(const_sp_db));
142 #endif
143 #if ENABLE_FEATURE_CLEAN_UP
144                 atexit(free_static);
145 #endif
146         }
147         return ptr_to_statics;
148 }
149
150 /* Internal functions */
151
152 /* Divide the passwd/group/shadow record in fields
153  * by substituting the given delimeter
154  * e.g. ':' or ',' with '\0'.
155  * Returns the number of fields found.
156  * Strips leading and trailing whitespace in fields.
157  */
158 static int tokenize(char *buffer, int ch)
159 {
160         char *p = buffer;
161         char *s = p;
162         int num_fields = 0;
163
164         for (;;) {
165                 if (isblank(*s)) {
166                         overlapping_strcpy(s, skip_whitespace(s));
167                 }
168                 if (*p == ch || *p == '\0') {
169                         char *end = p;
170                         while (p != s && isblank(p[-1]))
171                                 p--;
172                         if (p != end)
173                                 overlapping_strcpy(p, end);
174                         num_fields++;
175                         if (*end == '\0') {
176                                 S.tokenize_end = p + 1;
177                                 return num_fields;
178                         }
179                         *p = '\0';
180                         s = p + 1;
181                 }
182                 p++;
183         }
184 }
185
186 /* Returns !NULL on success and matching line broken up in fields by '\0' in buf.
187  * We require the expected number of fields to be found.
188  */
189 static char *parse_common(FILE *fp, struct passdb *db,
190                 const char *key, int field_pos)
191 {
192         int count = 0;
193         char *buf;
194
195         while ((buf = xmalloc_fgetline(fp)) != NULL) {
196                 count++;
197                 /* Skip empty lines, comment lines */
198                 if (buf[0] == '\0' || buf[0] == '#')
199                         goto free_and_next;
200                 if (tokenize(buf, ':') != db->numfields) {
201                         /* number of fields is wrong */
202                         bb_error_msg("bad record at %s:%u", db->filename, count);
203                         goto free_and_next;
204                 }
205
206                 if (!key) {
207                         /* no key specified: sequential read, return a record */
208                         break;
209                 }
210                 if (strcmp(key, nth_string(buf, field_pos)) == 0) {
211                         /* record found */
212                         break;
213                 }
214  free_and_next:
215                 free(buf);
216         }
217
218         S.string_size = S.tokenize_end - buf;
219 /*
220  * Ugly hack: group db requires additional buffer space
221  * for members[] array. If there is only one group, we need space
222  * for 3 pointers: alignment padding, group name, NULL.
223  * +1 for every additional group.
224  */
225         if (buf && db->numfields == sizeof(GR_DEF)-1) { /* if we read group file... */
226                 int cnt = 3;
227                 char *p = buf;
228                 while (p < S.tokenize_end)
229                         if (*p++ == ',')
230                                 cnt++;
231                 S.string_size += cnt * sizeof(char*);
232 //bb_error_msg("+%d words = %u key:%s buf:'%s'", cnt, S.string_size, key, buf);
233                 buf = xrealloc(buf, S.string_size);
234         }
235
236         return buf;
237 }
238
239 static char *parse_file(struct passdb *db,
240                 const char *key, int field_pos)
241 {
242         char *buf = NULL;
243         FILE *fp = fopen_for_read(db->filename);
244
245         if (fp) {
246                 buf = parse_common(fp, db, key, field_pos);
247                 fclose(fp);
248         }
249         return buf;
250 }
251
252 /* Convert passwd/group/shadow file record in buffer to a struct */
253 static void *convert_to_struct(struct passdb *db,
254                 char *buffer, void *result)
255 {
256         const char *def = db->def;
257         const uint8_t *off = db->off;
258
259         /* For consistency, zero out all fields */
260         memset(result, 0, db->size_of);
261
262         for (;;) {
263                 void *member = (char*)result + (*off++);
264
265                 if ((*def | 0x20) == 's') { /* s or S */
266                         *(char **)member = (char*)buffer;
267                         if (!buffer[0] && (*def == 'S')) {
268                                 errno = EINVAL;
269                         }
270                 }
271                 if (*def == 'I') {
272                         *(int *)member = bb_strtou(buffer, NULL, 10);
273                 }
274 #if ENABLE_USE_BB_SHADOW
275                 if (*def == 'l') {
276                         long n = -1;
277                         if (buffer[0])
278                                 n = bb_strtol(buffer, NULL, 10);
279                         *(long *)member = n;
280                 }
281 #endif
282                 if (*def == 'm') {
283                         char **members;
284                         int i = tokenize(buffer, ',');
285
286                         /* Store members[] after buffer's end.
287                          * This is safe ONLY because there is a hack
288                          * in parse_common() which allocates additional space
289                          * at the end of malloced buffer!
290                          */
291                         members = (char **)
292                                 ( ((intptr_t)S.tokenize_end + sizeof(members[0]))
293                                 & -(intptr_t)sizeof(members[0])
294                                 );
295
296                         ((struct group *)result)->gr_mem = members;
297                         while (--i >= 0) {
298                                 if (buffer[0]) {
299                                         *members++ = buffer;
300                                         // bb_error_msg("member[]='%s'", buffer);
301                                 }
302                                 buffer += strlen(buffer) + 1;
303                         }
304                         *members = NULL;
305                 }
306                 /* def "r" does nothing */
307
308                 def++;
309                 if ((unsigned char)*def <= (unsigned char)' ')
310                         break;
311                 buffer += strlen(buffer) + 1;
312         }
313
314         if (errno)
315                 result = NULL;
316         return result;
317 }
318
319 /****** getXXnam/id_r */
320
321 static int FAST_FUNC getXXnam_r(const char *name, uintptr_t db_and_field_pos,
322                 char *buffer, size_t buflen,
323                 void *result)
324 {
325         void *struct_buf = *(void**)result;
326         char *buf;
327         struct passdb *db = &get_S()->db[db_and_field_pos >> 2];
328
329         *(void**)result = NULL;
330         buf = parse_file(db, name, 0 /*db_and_field_pos & 3*/);
331         /* "db_and_field_pos & 3" is commented out since so far we don't implement
332          * getXXXid_r() functions which would use that to pass 2 here */
333         if (buf) {
334                 size_t size = S.tokenize_end - buf;
335                 if (size > buflen) {
336                         errno = ERANGE;
337                 } else {
338                         memcpy(buffer, buf, size);
339                         *(void**)result = convert_to_struct(db, buffer, struct_buf);
340                 }
341                 free(buf);
342         }
343         /* "The reentrant functions return zero on success.
344          * In case of error, an error number is returned."
345          * NB: not finding the record is also a "success" here:
346          */
347         return errno;
348 }
349
350 int FAST_FUNC getpwnam_r(const char *name, struct passwd *struct_buf,
351                 char *buffer, size_t buflen,
352                 struct passwd **result)
353 {
354         /* Why the "store buffer address in result" trick?
355          * This way, getXXnam_r has the same ABI signature as getpwnam_r,
356          * hopefully compiler can optimize tail call better in this case.
357          */
358         *result = struct_buf;
359         return getXXnam_r(name, (0 << 2) + 0, buffer, buflen, result);
360 }
361 #if ENABLE_USE_BB_SHADOW
362 int FAST_FUNC getspnam_r(const char *name, struct spwd *struct_buf, char *buffer, size_t buflen,
363                 struct spwd **result)
364 {
365         *result = struct_buf;
366         return getXXnam_r(name, (2 << 2) + 0, buffer, buflen, result);
367 }
368 #endif
369
370 /****** getXXent_r */
371
372 static int FAST_FUNC getXXent_r(void *struct_buf, char *buffer, size_t buflen,
373                 void *result,
374                 unsigned db_idx)
375 {
376         char *buf;
377         struct passdb *db = &get_S()->db[db_idx];
378
379         *(void**)result = NULL;
380
381         if (!db->fp) {
382                 db->fp = fopen_for_read(db->filename);
383                 if (!db->fp) {
384                         return errno;
385                 }
386                 close_on_exec_on(fileno(db->fp));
387         }
388
389         buf = parse_common(db->fp, db, /*no search key:*/ NULL, 0);
390         if (buf) {
391                 size_t size = S.tokenize_end - buf;
392                 if (size > buflen) {
393                         errno = ERANGE;
394                 } else {
395                         memcpy(buffer, buf, size);
396                         *(void**)result = convert_to_struct(db, buffer, struct_buf);
397                 }
398                 free(buf);
399         }
400         /* "The reentrant functions return zero on success.
401          * In case of error, an error number is returned."
402          * NB: not finding the record is also a "success" here:
403          */
404         return errno;
405 }
406
407 int FAST_FUNC getpwent_r(struct passwd *struct_buf, char *buffer, size_t buflen, struct passwd **result)
408 {
409         return getXXent_r(struct_buf, buffer, buflen, result, 0);
410 }
411
412 /****** getXXnam/id */
413
414 static void* FAST_FUNC getXXnam(const char *name, unsigned db_and_field_pos)
415 {
416         char *buf;
417         void *result;
418         struct passdb *db = &get_S()->db[db_and_field_pos >> 2];
419
420         result = NULL;
421
422         if (!db->fp) {
423                 db->fp = fopen_for_read(db->filename);
424                 if (!db->fp) {
425                         return NULL;
426                 }
427                 close_on_exec_on(fileno(db->fp));
428         }
429
430         buf = parse_common(db->fp, db, name, db_and_field_pos & 3);
431         if (buf) {
432                 free(db->malloced);
433                 /* We enlarge buf and move string data up, freeing space
434                  * for struct passwd/group/spwd at the beginning. This way,
435                  * entire result of getXXnam is in a single malloced block.
436                  * This enables easy creation of xmalloc_getpwnam() API.
437                  */
438                 db->malloced = buf = xrealloc(buf, db->size_of + S.string_size);
439                 memmove(buf + db->size_of, buf, S.string_size);
440                 result = convert_to_struct(db, buf + db->size_of, buf);
441         }
442         return result;
443 }
444
445 struct passwd* FAST_FUNC getpwnam(const char *name)
446 {
447         return getXXnam(name, (0 << 2) + 0);
448 }
449 struct group* FAST_FUNC getgrnam(const char *name)
450 {
451         return getXXnam(name, (1 << 2) + 0);
452 }
453 struct passwd* FAST_FUNC getpwuid(uid_t id)
454 {
455         return getXXnam(utoa(id), (0 << 2) + 2);
456 }
457 struct group* FAST_FUNC getgrgid(gid_t id)
458 {
459         return getXXnam(utoa(id), (1 << 2) + 2);
460 }
461
462 /****** end/setXXend */
463
464 void FAST_FUNC endpwent(void)
465 {
466         if (has_S && S.db[0].fp) {
467                 fclose(S.db[0].fp);
468                 S.db[0].fp = NULL;
469         }
470 }
471 void FAST_FUNC setpwent(void)
472 {
473         if (has_S && S.db[0].fp) {
474                 rewind(S.db[0].fp);
475         }
476 }
477 void FAST_FUNC endgrent(void)
478 {
479         if (has_S && S.db[1].fp) {
480                 fclose(S.db[1].fp);
481                 S.db[1].fp = NULL;
482         }
483 }
484
485 /****** initgroups and getgrouplist */
486
487 static gid_t* FAST_FUNC getgrouplist_internal(int *ngroups_ptr,
488                 const char *user, gid_t gid)
489 {
490         FILE *fp;
491         gid_t *group_list;
492         int ngroups;
493
494         /* We alloc space for 8 gids at a time. */
495         group_list = xzalloc(8 * sizeof(group_list[0]));
496         group_list[0] = gid;
497         ngroups = 1;
498
499         fp = fopen_for_read(_PATH_GROUP);
500         if (fp) {
501                 struct passdb *db = &get_S()->db[1];
502                 char *buf;
503                 while ((buf = parse_common(fp, db, NULL, 0)) != NULL) {
504                         char **m;
505                         struct group group;
506                         if (!convert_to_struct(db, buf, &group))
507                                 goto next;
508                         if (group.gr_gid == gid)
509                                 goto next;
510                         for (m = group.gr_mem; *m; m++) {
511                                 if (strcmp(*m, user) != 0)
512                                         continue;
513                                 group_list = xrealloc_vector(group_list, /*8=2^3:*/ 3, ngroups);
514                                 group_list[ngroups++] = group.gr_gid;
515                                 break;
516                         }
517  next:
518                         free(buf);
519                 }
520                 fclose(fp);
521         }
522         *ngroups_ptr = ngroups;
523         return group_list;
524 }
525
526 int FAST_FUNC initgroups(const char *user, gid_t gid)
527 {
528         int ngroups;
529         gid_t *group_list = getgrouplist_internal(&ngroups, user, gid);
530
531         ngroups = setgroups(ngroups, group_list);
532         free(group_list);
533         return ngroups;
534 }
535
536 int FAST_FUNC getgrouplist(const char *user, gid_t gid, gid_t *groups, int *ngroups)
537 {
538         int ngroups_old = *ngroups;
539         gid_t *group_list = getgrouplist_internal(ngroups, user, gid);
540
541         if (*ngroups <= ngroups_old) {
542                 ngroups_old = *ngroups;
543                 memcpy(groups, group_list, ngroups_old * sizeof(groups[0]));
544         } else {
545                 ngroups_old = -1;
546         }
547         free(group_list);
548         return ngroups_old;
549 }