gr_util.c revision 267654
1/*-
2 * Copyright (c) 2008 Sean C. Farley <scf@FreeBSD.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer,
10 *    without modification, immediately at the beginning of the file.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: releng/9.3/lib/libutil/gr_util.c 236451 2012-06-02 15:13:28Z bapt $");
29
30#include <sys/param.h>
31#include <sys/errno.h>
32#include <sys/stat.h>
33
34#include <ctype.h>
35#include <err.h>
36#include <fcntl.h>
37#include <grp.h>
38#include <inttypes.h>
39#include <libutil.h>
40#include <paths.h>
41#include <stdbool.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <unistd.h>
46
47struct group_storage {
48	struct group	 gr;
49	char		*members[];
50};
51
52static int lockfd = -1;
53static char group_dir[PATH_MAX];
54static char group_file[PATH_MAX];
55static char tempname[PATH_MAX];
56static int initialized;
57
58static const char group_line_format[] = "%s:%s:%ju:";
59
60/*
61 * Initialize statics
62 */
63int
64gr_init(const char *dir, const char *group)
65{
66	if (dir == NULL) {
67		strcpy(group_dir, _PATH_ETC);
68	} else {
69		if (strlen(dir) >= sizeof(group_dir)) {
70			errno = ENAMETOOLONG;
71			return (-1);
72		}
73		strcpy(group_dir, dir);
74	}
75
76	if (group == NULL) {
77		if (dir == NULL) {
78			strcpy(group_file, _PATH_GROUP);
79		} else if (snprintf(group_file, sizeof(group_file), "%s/group",
80			group_dir) > (int)sizeof(group_file)) {
81			errno = ENAMETOOLONG;
82			return (-1);
83		}
84	} else {
85		if (strlen(group) >= sizeof(group_file)) {
86			errno = ENAMETOOLONG;
87			return (-1);
88		}
89		strcpy(group_file, group);
90	}
91	initialized = 1;
92	return (0);
93}
94
95/*
96 * Lock the group file
97 */
98int
99gr_lock(void)
100{
101	if (*group_file == '\0')
102		return (-1);
103
104	for (;;) {
105		struct stat st;
106
107		lockfd = open(group_file, O_RDONLY, 0);
108		if (lockfd < 0 || fcntl(lockfd, F_SETFD, 1) == -1)
109			err(1, "%s", group_file);
110		if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
111			if (errno == EWOULDBLOCK) {
112				errx(1, "the group file is busy");
113			} else {
114				err(1, "could not lock the group file: ");
115			}
116		}
117		if (fstat(lockfd, &st) == -1)
118			err(1, "fstat() failed: ");
119		if (st.st_nlink != 0)
120			break;
121		close(lockfd);
122		lockfd = -1;
123	}
124	return (lockfd);
125}
126
127/*
128 * Create and open a presmuably safe temp file for editing group data
129 */
130int
131gr_tmp(int mfd)
132{
133	char buf[8192];
134	ssize_t nr;
135	const char *p;
136	int tfd;
137
138	if (*group_file == '\0')
139		return (-1);
140	if ((p = strrchr(group_file, '/')))
141		++p;
142	else
143		p = group_file;
144	if (snprintf(tempname, sizeof(tempname), "%.*sgroup.XXXXXX",
145		(int)(p - group_file), group_file) >= (int)sizeof(tempname)) {
146		errno = ENAMETOOLONG;
147		return (-1);
148	}
149	if ((tfd = mkstemp(tempname)) == -1)
150		return (-1);
151	if (mfd != -1) {
152		while ((nr = read(mfd, buf, sizeof(buf))) > 0)
153			if (write(tfd, buf, (size_t)nr) != nr)
154				break;
155		if (nr != 0) {
156			unlink(tempname);
157			*tempname = '\0';
158			close(tfd);
159			return (-1);
160		}
161	}
162	return (tfd);
163}
164
165/*
166 * Copy the group file from one descriptor to another, replacing, deleting
167 * or adding a single record on the way.
168 */
169int
170gr_copy(int ffd, int tfd, const struct group *gr, struct group *old_gr)
171{
172	char buf[8192], *end, *line, *p, *q, *r, t;
173	struct group *fgr;
174	const struct group *sgr;
175	size_t len;
176	int eof, readlen;
177
178	sgr = gr;
179	if (gr == NULL) {
180		line = NULL;
181		if (old_gr == NULL)
182			return (-1);
183		sgr = old_gr;
184	} else if ((line = gr_make(gr)) == NULL)
185		return (-1);
186
187	eof = 0;
188	len = 0;
189	p = q = end = buf;
190	for (;;) {
191		/* find the end of the current line */
192		for (p = q; q < end && *q != '\0'; ++q)
193			if (*q == '\n')
194				break;
195
196		/* if we don't have a complete line, fill up the buffer */
197		if (q >= end) {
198			if (eof)
199				break;
200			if ((size_t)(q - p) >= sizeof(buf)) {
201				warnx("group line too long");
202				errno = EINVAL; /* hack */
203				goto err;
204			}
205			if (p < end) {
206				q = memmove(buf, p, end -p);
207				end -= p - buf;
208			} else {
209				p = q = end = buf;
210			}
211			readlen = read(ffd, end, sizeof(buf) - (end -buf));
212			if (readlen == -1)
213				goto err;
214			else
215				len = (size_t)readlen;
216			if (len == 0 && p == buf)
217				break;
218			end += len;
219			len = end - buf;
220			if (len < (ssize_t)sizeof(buf)) {
221				eof = 1;
222				if (len > 0 && buf[len -1] != '\n')
223					++len, *end++ = '\n';
224			}
225			continue;
226		}
227
228		/* is it a blank line or a comment? */
229		for (r = p; r < q && isspace(*r); ++r)
230			/* nothing */;
231		if (r == q || *r == '#') {
232			/* yep */
233			if (write(tfd, p, q -p + 1) != q - p + 1)
234				goto err;
235			++q;
236			continue;
237		}
238
239		/* is it the one we're looking for? */
240
241		t = *q;
242		*q = '\0';
243
244		fgr = gr_scan(r);
245
246		/* fgr is either a struct group for the current line,
247		 * or NULL if the line is malformed.
248		 */
249
250		*q = t;
251		if (fgr == NULL || fgr->gr_gid != sgr->gr_gid) {
252			/* nope */
253			if (fgr != NULL)
254				free(fgr);
255			if (write(tfd, p, q - p + 1) != q - p + 1)
256				goto err;
257			++q;
258			continue;
259		}
260		if (old_gr && !gr_equal(fgr, old_gr)) {
261			warnx("entry inconsistent");
262			free(fgr);
263			errno = EINVAL; /* hack */
264			goto err;
265		}
266		free(fgr);
267
268		/* it is, replace or remove it */
269		if (line != NULL) {
270			len = strlen(line);
271			if (write(tfd, line, len) != (int) len)
272				goto err;
273		} else {
274			/* when removed, avoid the \n */
275			q++;
276		}
277		/* we're done, just copy the rest over */
278		for (;;) {
279			if (write(tfd, q, end - q) != end - q)
280				goto err;
281			q = buf;
282			readlen = read(ffd, buf, sizeof(buf));
283			if (readlen == 0)
284				break;
285			else
286				len = (size_t)readlen;
287			if (readlen == -1)
288				goto err;
289			end = buf + len;
290		}
291		goto done;
292	}
293
294	/* if we got here, we didn't find the old entry */
295	if (line == NULL) {
296		errno = ENOENT;
297		goto err;
298	}
299	len = strlen(line);
300	if ((size_t)write(tfd, line, len) != len ||
301	   write(tfd, "\n", 1) != 1)
302		goto err;
303 done:
304	if (line != NULL)
305		free(line);
306	return (0);
307 err:
308	if (line != NULL)
309		free(line);
310	return (-1);
311}
312
313/*
314 * Regenerate the group file
315 */
316int
317gr_mkdb(void)
318{
319	return (rename(tempname, group_file));
320}
321
322/*
323 * Clean up. Preserver errno for the caller's convenience.
324 */
325void
326gr_fini(void)
327{
328	int serrno;
329
330	if (!initialized)
331		return;
332	initialized = 0;
333	serrno = errno;
334	if (*tempname != '\0') {
335		unlink(tempname);
336		*tempname = '\0';
337	}
338	if (lockfd != -1)
339		close(lockfd);
340	errno = serrno;
341}
342
343/*
344 * Compares two struct group's.
345 */
346int
347gr_equal(const struct group *gr1, const struct group *gr2)
348{
349	int gr1_ndx;
350	int gr2_ndx;
351	bool found;
352
353	/* Check that the non-member information is the same. */
354	if (gr1->gr_name == NULL || gr2->gr_name == NULL) {
355		if (gr1->gr_name != gr2->gr_name)
356			return (false);
357	} else if (strcmp(gr1->gr_name, gr2->gr_name) != 0)
358		return (false);
359	if (gr1->gr_passwd == NULL || gr2->gr_passwd == NULL) {
360		if (gr1->gr_passwd != gr2->gr_passwd)
361			return (false);
362	} else if (strcmp(gr1->gr_passwd, gr2->gr_passwd) != 0)
363		return (false);
364	if (gr1->gr_gid != gr2->gr_gid)
365		return (false);
366
367	/* Check all members in both groups. */
368	if (gr1->gr_mem == NULL || gr2->gr_mem == NULL) {
369		if (gr1->gr_mem != gr2->gr_mem)
370			return (false);
371	} else {
372		for (found = false, gr1_ndx = 0; gr1->gr_mem[gr1_ndx] != NULL;
373		    gr1_ndx++) {
374			for (gr2_ndx = 0; gr2->gr_mem[gr2_ndx] != NULL;
375			    gr2_ndx++)
376				if (strcmp(gr1->gr_mem[gr1_ndx],
377				    gr2->gr_mem[gr2_ndx]) == 0) {
378					found = true;
379					break;
380				}
381			if (!found)
382				return (false);
383		}
384
385		/* Check that group2 does not have more members than group1. */
386		if (gr2->gr_mem[gr1_ndx] != NULL)
387			return (false);
388	}
389
390	return (true);
391}
392
393/*
394 * Make a group line out of a struct group.
395 */
396char *
397gr_make(const struct group *gr)
398{
399	char *line;
400	size_t line_size;
401	int ndx;
402
403	/* Calculate the length of the group line. */
404	line_size = snprintf(NULL, 0, group_line_format, gr->gr_name,
405	    gr->gr_passwd, (uintmax_t)gr->gr_gid) + 1;
406	if (gr->gr_mem != NULL) {
407		for (ndx = 0; gr->gr_mem[ndx] != NULL; ndx++)
408			line_size += strlen(gr->gr_mem[ndx]) + 1;
409		if (ndx > 0)
410			line_size--;
411	}
412
413	/* Create the group line and fill it. */
414	if ((line = malloc(line_size)) == NULL)
415		return (NULL);
416	snprintf(line, line_size, group_line_format, gr->gr_name, gr->gr_passwd,
417	    (uintmax_t)gr->gr_gid);
418	if (gr->gr_mem != NULL)
419		for (ndx = 0; gr->gr_mem[ndx] != NULL; ndx++) {
420			strcat(line, gr->gr_mem[ndx]);
421			if (gr->gr_mem[ndx + 1] != NULL)
422				strcat(line, ",");
423		}
424
425	return (line);
426}
427
428/*
429 * Duplicate a struct group.
430 */
431struct group *
432gr_dup(const struct group *gr)
433{
434	char *dst;
435	size_t len;
436	struct group_storage *gs;
437	int ndx;
438	int num_mem;
439
440	/* Calculate size of the group. */
441	len = sizeof(*gs);
442	if (gr->gr_name != NULL)
443		len += strlen(gr->gr_name) + 1;
444	if (gr->gr_passwd != NULL)
445		len += strlen(gr->gr_passwd) + 1;
446	if (gr->gr_mem != NULL) {
447		for (num_mem = 0; gr->gr_mem[num_mem] != NULL; num_mem++)
448			len += strlen(gr->gr_mem[num_mem]) + 1;
449		len += (num_mem + 1) * sizeof(*gr->gr_mem);
450	} else
451		num_mem = -1;
452
453	/* Create new group and copy old group into it. */
454	if ((gs = calloc(1, len)) == NULL)
455		return (NULL);
456	dst = (char *)&gs->members[num_mem + 1];
457	if (gr->gr_name != NULL) {
458		gs->gr.gr_name = dst;
459		dst = stpcpy(gs->gr.gr_name, gr->gr_name) + 1;
460	}
461	if (gr->gr_passwd != NULL) {
462		gs->gr.gr_passwd = dst;
463		dst = stpcpy(gs->gr.gr_passwd, gr->gr_passwd) + 1;
464	}
465	gs->gr.gr_gid = gr->gr_gid;
466	if (gr->gr_mem != NULL) {
467		gs->gr.gr_mem = gs->members;
468		for (ndx = 0; ndx < num_mem; ndx++) {
469			gs->gr.gr_mem[ndx] = dst;
470			dst = stpcpy(gs->gr.gr_mem[ndx], gr->gr_mem[ndx]) + 1;
471		}
472		gs->gr.gr_mem[ndx] = NULL;
473	}
474
475	return (&gs->gr);
476}
477
478/*
479 * Scan a line and place it into a group structure.
480 */
481static bool
482__gr_scan(char *line, struct group *gr)
483{
484	char *loc;
485	int ndx;
486
487	/* Assign non-member information to structure. */
488	gr->gr_name = line;
489	if ((loc = strchr(line, ':')) == NULL)
490		return (false);
491	*loc = '\0';
492	gr->gr_passwd = loc + 1;
493	if (*gr->gr_passwd == ':')
494		*gr->gr_passwd = '\0';
495	else {
496		if ((loc = strchr(loc + 1, ':')) == NULL)
497			return (false);
498		*loc = '\0';
499	}
500	if (sscanf(loc + 1, "%u", &gr->gr_gid) != 1)
501		return (false);
502
503	/* Assign member information to structure. */
504	if ((loc = strchr(loc + 1, ':')) == NULL)
505		return (false);
506	line = loc + 1;
507	gr->gr_mem = NULL;
508	ndx = 0;
509	do {
510		gr->gr_mem = reallocf(gr->gr_mem, sizeof(*gr->gr_mem) *
511		    (ndx + 1));
512		if (gr->gr_mem == NULL)
513			return (false);
514
515		/* Skip locations without members (i.e., empty string). */
516		do {
517			gr->gr_mem[ndx] = strsep(&line, ",");
518		} while (gr->gr_mem[ndx] != NULL && *gr->gr_mem[ndx] == '\0');
519	} while (gr->gr_mem[ndx++] != NULL);
520
521	return (true);
522}
523
524/*
525 * Create a struct group from a line.
526 */
527struct group *
528gr_scan(const char *line)
529{
530	struct group gr;
531	char *line_copy;
532	struct group *new_gr;
533
534	if ((line_copy = strdup(line)) == NULL)
535		return (NULL);
536	if (!__gr_scan(line_copy, &gr)) {
537		free(line_copy);
538		return (NULL);
539	}
540	new_gr = gr_dup(&gr);
541	free(line_copy);
542	if (gr.gr_mem != NULL)
543		free(gr.gr_mem);
544
545	return (new_gr);
546}
547