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