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