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