summaryrefslogtreecommitdiffhomepage
path: root/libpwdgrp/pwd_grp.c
blob: 539d2b01fdd1a9a20a95c3beaef86353453676e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/* vi: set sw=4 ts=4: */
/* Copyright (C) 2014 Tito Ragusa <farmatito@tiscali.it>
 *
 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
 */
/* This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY!!
 *
 * Rewrite of some parts. Main differences are:
 *
 * 1) the buffer for getpwuid, getgrgid, getpwnam, getgrnam is dynamically
 *    allocated and reused by later calls.
 *    If ENABLE_FEATURE_CLEAN_UP is set the buffers are freed at program
 *    exit using the atexit function to make valgrind happy.
 * 2) the passwd/group files:
 *      a) must contain the expected number of fields (as per count of field
 *         delimeters ":") or we will complain with a error message.
 *      b) leading or trailing whitespace in fields is stripped.
 *      c) some fields are not allowed to be empty (e.g. username, uid/gid,
 *         homedir, shell) and in this case NULL is returned and errno is
 *         set to EINVAL. This behaviour could be easily changed by
 *         modifying PW_DEF, GR_DEF, SP_DEF strings (uppercase
 *         makes a field mandatory).
 *      d) the string representing uid/gid must be convertible by strtoXX
 *         functions, or errno is set to EINVAL.
 *      e) leading or trailing whitespace in group member names are stripped.
 * 3) the internal function for getgrouplist uses dynamically allocated buffer.
 * 4) at the moment only the functions really used by busybox code are
 *    implemented, if you need a particular missing function it should be
 *    easy to write it by using the internal common code.
 */

#include "libbb.h"

struct const_passdb {
	const char *filename;
	const char def[10];
	const uint8_t off[9];
	uint8_t numfields;
};
struct passdb {
	const char *filename;
	const char def[10];
	const uint8_t off[9];
	uint8_t numfields;
	FILE *fp;
	char *malloced;
	char struct_result[0
				| sizeof(struct passwd)
				| sizeof(struct group)
	IF_USE_BB_SHADOW(       | sizeof(struct spwd)  )
	/* bitwise OR above is poor man's max(a,b,c) */
	];
};

/* S = string not empty, s = string maybe empty,
 * I = uid,gid, l = long maybe empty, m = members,
 * r = reserved
 */
#define PW_DEF "SsIIsSS"
#define GR_DEF "SsIm"
#define SP_DEF "Ssllllllr"

static const struct const_passdb const_pw_db = {
	_PATH_PASSWD, PW_DEF,
	{
		offsetof(struct passwd, pw_name),       /* 0 S */
		offsetof(struct passwd, pw_passwd),     /* 1 s */
		offsetof(struct passwd, pw_uid),        /* 2 I */
		offsetof(struct passwd, pw_gid),        /* 3 I */
		offsetof(struct passwd, pw_gecos),      /* 4 s */
		offsetof(struct passwd, pw_dir),        /* 5 S */
		offsetof(struct passwd, pw_shell)       /* 6 S */
	},
	sizeof(PW_DEF)-1
};
static const struct const_passdb const_gr_db = {
	_PATH_GROUP, GR_DEF,
	{
		offsetof(struct group, gr_name),        /* 0 S */
		offsetof(struct group, gr_passwd),      /* 1 s */
		offsetof(struct group, gr_gid),         /* 2 I */
		offsetof(struct group, gr_mem)          /* 3 m (char **) */
	},
	sizeof(GR_DEF)-1
};
#if ENABLE_USE_BB_SHADOW
static const struct const_passdb const_sp_db = {
	_PATH_SHADOW, SP_DEF,
	{
		offsetof(struct spwd, sp_namp),         /* 0 S Login name */
		offsetof(struct spwd, sp_pwdp),         /* 1 s Encrypted password */
		offsetof(struct spwd, sp_lstchg),       /* 2 l */
		offsetof(struct spwd, sp_min),          /* 3 l */
		offsetof(struct spwd, sp_max),          /* 4 l */
		offsetof(struct spwd, sp_warn),         /* 5 l */
		offsetof(struct spwd, sp_inact),        /* 6 l */
		offsetof(struct spwd, sp_expire),       /* 7 l */
		offsetof(struct spwd, sp_flag)          /* 8 r Reserved */
	},
	sizeof(SP_DEF)-1
};
#endif

/* We avoid having big global data. */
struct statics {
	/* It's ok to use same buffer (db[0].struct_result) for getpwuid and getpwnam.
	 * Manpage says:
	 * "The return value may point to a static area, and may be overwritten
	 * by subsequent calls to getpwent(), getpwnam(), or getpwuid()."
	 */
	struct passdb db[2 + ENABLE_USE_BB_SHADOW];
	char *tokenize_end;
};

static struct statics *ptr_to_statics;
#define S     (*ptr_to_statics)
#define has_S (ptr_to_statics)

#if ENABLE_FEATURE_CLEAN_UP
static void free_static(void)
{
    	free(S.db[0].malloced);
	free(S.db[1].malloced);
# if ENABLE_USE_BB_SHADOW
	S.db[2].malloced);
# endif
	free(ptr_to_statics);
}
#endif

static struct statics *get_S(void)
{
	if (!ptr_to_statics) {
		ptr_to_statics = xzalloc(sizeof(S));
		memcpy(&S.db[0], &const_pw_db, sizeof(const_pw_db));
		memcpy(&S.db[1], &const_gr_db, sizeof(const_gr_db));
#if ENABLE_USE_BB_SHADOW
		memcpy(&S.db[2], &const_sp_db, sizeof(const_sp_db));
#endif
#if ENABLE_FEATURE_CLEAN_UP
		atexit(free_static);
#endif
	}
	return ptr_to_statics;
}

/* Internal functions */

/* Divide the passwd/group/shadow record in fields
 * by substituting the given delimeter
 * e.g. ':' or ',' with '\0'.
 * Returns the number of fields found.
 * Strips leading and trailing whitespace in fields.
 */
static int tokenize(char *buffer, int ch)
{
	char *p = buffer;
	char *s = p;
	int num_fields = 0;

	for (;;) {
		if (isblank(*s)) {
			overlapping_strcpy(s, skip_whitespace(s));
		}
		if (*p == ch || *p == '\0') {
			char *end = p;
			while (p != s && isblank(p[-1]))
				p--;
			if (p != end)
				overlapping_strcpy(p, end);
			num_fields++;
			if (*end == '\0') {
				S.tokenize_end = p + 1;
				return num_fields;
			}
			*p = '\0';
			s = p + 1;
		}
		p++;
	}
}

/* Returns !NULL on success and matching line broken up in fields by '\0' in buf.
 * We require the expected number of fields to be found.
 */
static char *parse_common(FILE *fp, const char *filename,
		int n_fields,
		const char *key, int field_pos)
{
	int count = 0;
	char *buf;

	while ((buf = xmalloc_fgetline(fp)) != NULL) {
		count++;
		/* Skip empty lines, comment lines */
		if (buf[0] == '\0' || buf[0] == '#')
			goto free_and_next;
		if (tokenize(buf, ':') != n_fields) {
			/* number of fields is wrong */
			bb_error_msg("bad record at %s:%u", filename, count);
			goto free_and_next;
		}

/* Ugly hack: group db requires aqdditional buffer space
 * for members[] array. If there is only one group, we need space
 * for 3 pointers: alignment padding, group name, NULL.
 * +1 for every additional group.
 */
		if (n_fields == sizeof(GR_DEF)-1) { /* if we read group file */
			int resize = 3;
			char *p = buf;
			while (*p)
				if (*p++ == ',')
					resize++;
			resize *= sizeof(char**);
			resize += S.tokenize_end - buf;
			buf = xrealloc(buf, resize);
		}

		if (!key) {
			/* no key specified: sequential read, return a record */
			break;
		}
		if (strcmp(key, nth_string(buf, field_pos)) == 0) {
			/* record found */
			break;
		}
 free_and_next:
		free(buf);
	}

	return buf;
}

static char *parse_file(const char *filename,
		int n_fields,
		const char *key, int field_pos)
{
	char *buf = NULL;
	FILE *fp = fopen_for_read(filename);

	if (fp) {
		buf = parse_common(fp, filename, n_fields, key, field_pos);
		fclose(fp);
	}
	return buf;
}

/* Convert passwd/group/shadow file record in buffer to a struct */
static void *convert_to_struct(struct passdb *db,
		char *buffer, void *result)
{
	const char *def = db->def;
	const uint8_t *off = db->off;

/* TODO? for consistency, zero out all fields */
/*	memset(result, 0, size_of_result);*/

	for (;;) {
		void *member = (char*)result + (*off++);

		if ((*def | 0x20) == 's') { /* s or S */
			*(char **)member = (char*)buffer;
			if (!buffer[0] && (*def == 'S')) {
				errno = EINVAL;
			}
		}
		if (*def == 'I') {
			*(int *)member = bb_strtou(buffer, NULL, 10);
		}
#if ENABLE_USE_BB_SHADOW
		if (*def == 'l') {
			long n = -1;
			if (buffer[0])
				n = bb_strtol(buffer, NULL, 10);
			*(long *)member = n;
		}
#endif
		if (*def == 'm') {
			char **members;
			int i = tokenize(buffer, ',');

			/* Store members[] after buffer's end.
			 * This is safe ONLY because there is a hack
			 * in parse_common() which allocates additional space
			 * at the end of malloced buffer!
			 */
			members = (char **)
				( ((intptr_t)S.tokenize_end + sizeof(char**))
				& -(intptr_t)sizeof(char**)
				);

			((struct group *)result)->gr_mem = members;
			while (--i >= 0) {
				*members++ = buffer;
				buffer += strlen(buffer) + 1;
			}
			*members = NULL;
		}
		/* def "r" does nothing */

		def++;
		if (*def == '\0')
			break;
		buffer += strlen(buffer) + 1;
	}

	if (errno)
		result = NULL;
	return result;
}

/****** getXXnam/id_r */

static int FAST_FUNC getXXnam_r(const char *name, uintptr_t db_and_field_pos,
		char *buffer, size_t buflen,
		void *result)
{
	void *struct_buf = *(void**)result;
	char *buf;
	struct passdb *db;
	get_S();
	db = &S.db[db_and_field_pos >> 2];

	*(void**)result = NULL;
	buf = parse_file(db->filename, db->numfields, name, db_and_field_pos & 3);
	if (buf) {
		size_t size = S.tokenize_end - buf;
		if (size > buflen) {
			errno = ERANGE;
		} else {
			memcpy(buffer, buf, size);
			*(void**)result = convert_to_struct(db, buffer, struct_buf);
		}
		free(buf);
	}
	/* "The reentrant functions return zero on success.
	 * In case of error, an error number is returned."
	 * NB: not finding the record is also a "success" here:
	 */
	return errno;
}

int FAST_FUNC getpwnam_r(const char *name, struct passwd *struct_buf,
		char *buffer, size_t buflen,
		struct passwd **result)
{
	/* Why the "store buffer address in result" trick?
	 * This way, getXXnam_r has the same ABI signature as getpwnam_r,
	 * hopefully compiler can optimize tail call better in this case.
	 */
	*result = struct_buf;
	return getXXnam_r(name, (0 << 2) + 0, buffer, buflen, result);
}
#if ENABLE_USE_BB_SHADOW
int FAST_FUNC getspnam_r(const char *name, struct spwd *struct_buf, char *buffer, size_t buflen,
		struct spwd **result)
{
	*result = struct_buf;
	return getXXnam_r(name, (2 << 2) + 0, buffer, buflen, result);
}
#endif

/****** getXXent_r */

static int FAST_FUNC getXXent_r(void *struct_buf, char *buffer, size_t buflen,
		void *result,
		unsigned db_idx)
{
	char *buf;
	struct passdb *db;
	get_S();
	db = &S.db[db_idx];

	*(void**)result = NULL;

	if (!db->fp) {
		db->fp = fopen_for_read(db->filename);
		if (!db->fp) {
			return errno;
		}
		close_on_exec_on(fileno(db->fp));
	}

	buf = parse_common(db->fp, db->filename, db->numfields, /*no search key:*/ NULL, 0);
	if (buf) {
		size_t size = S.tokenize_end - buf;
		if (size > buflen) {
			errno = ERANGE;
		} else {
			memcpy(buffer, buf, size);
			*(void**)result = convert_to_struct(db, buffer, struct_buf);
		}
		free(buf);
	}
	/* "The reentrant functions return zero on success.
	 * In case of error, an error number is returned."
	 * NB: not finding the record is also a "success" here:
	 */
	return errno;
}

int FAST_FUNC getpwent_r(struct passwd *struct_buf, char *buffer, size_t buflen, struct passwd **result)
{
	return getXXent_r(struct_buf, buffer, buflen, result, 0);
}

/****** getXXnam/id */

static void* FAST_FUNC getXXnam(const char *name, unsigned db_and_field_pos)
{
	char *buf;
	void *result;
	struct passdb *db;
	get_S();
	db = &S.db[db_and_field_pos >> 2];

	result = NULL;

	if (!db->fp) {
		db->fp = fopen_for_read(db->filename);
		if (!db->fp) {
			return NULL;
		}
		close_on_exec_on(fileno(db->fp));
	}

	buf = parse_common(db->fp, db->filename, db->numfields, name, db_and_field_pos & 3);
	if (buf) {
		free(db->malloced);
		db->malloced = buf;
		result = convert_to_struct(db, buf, db->struct_result);
	}
	return result;
}

struct passwd* FAST_FUNC getpwnam(const char *name)
{
	return getXXnam(name, (0 << 2) + 0);
}
struct group* FAST_FUNC getgrnam(const char *name)
{
	return getXXnam(name, (1 << 2) + 0);
}
struct passwd* FAST_FUNC getpwuid(uid_t id)
{
	return getXXnam(utoa(id), (0 << 2) + 2);
}
struct group* FAST_FUNC getgrgid(gid_t id)
{
	return getXXnam(utoa(id), (1 << 2) + 2);
}

/****** end/setXXend */

void FAST_FUNC endpwent(void)
{
	if (has_S && S.db[0].fp) {
		fclose(S.db[0].fp);
		S.db[0].fp = NULL;
	}
}
void FAST_FUNC setpwent(void)
{
	if (has_S && S.db[0].fp) {
		rewind(S.db[0].fp);
	}
}
void FAST_FUNC endgrent(void)
{
	if (has_S && S.db[1].fp) {
		fclose(S.db[1].fp);
		S.db[1].fp = NULL;
	}
}

/****** initgroups and getgrouplist */

static gid_t* FAST_FUNC getgrouplist_internal(int *ngroups_ptr,
		const char *user, gid_t gid)
{
	FILE *fp;
	gid_t *group_list;
	int ngroups;

	get_S();

	/* We alloc space for 8 gids at a time. */
	group_list = xzalloc(8 * sizeof(group_list[0]));
	group_list[0] = gid;
	ngroups = 1;

	fp = fopen_for_read(_PATH_GROUP);
	if (fp) {
		char *buf;
		while ((buf = parse_common(fp, _PATH_GROUP, sizeof(GR_DEF)-1, NULL, 0)) != NULL) {
			char **m;
			struct group group;
			if (!convert_to_struct(&S.db[1], buf, &group))
				goto next;
			if (group.gr_gid == gid)
				goto next;
			for (m = group.gr_mem; *m; m++) {
				if (strcmp(*m, user) != 0)
					continue;
				group_list = xrealloc_vector(group_list, /*8=2^3:*/ 3, ngroups);
				group_list[ngroups++] = group.gr_gid;
				break;
			}
 next:
			free(buf);
		}
		fclose(fp);
	}
	*ngroups_ptr = ngroups;
	return group_list;
}

int FAST_FUNC initgroups(const char *user, gid_t gid)
{
	int ngroups;
	gid_t *group_list = getgrouplist_internal(&ngroups, user, gid);

	ngroups = setgroups(ngroups, group_list);
	free(group_list);
	return ngroups;
}

int FAST_FUNC getgrouplist(const char *user, gid_t gid, gid_t *groups, int *ngroups)
{
	int ngroups_old = *ngroups;
	gid_t *group_list = getgrouplist_internal(ngroups, user, gid);

	if (*ngroups <= ngroups_old) {
		ngroups_old = *ngroups;
		memcpy(groups, group_list, ngroups_old * sizeof(groups[0]));
	} else {
		ngroups_old = -1;
	}
	free(group_list);
	return ngroups_old;
}