gr_util.c revision 245386
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: head/lib/libutil/gr_util.c 245386 2013-01-13 21:26:57Z mjg $");
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
47static int lockfd = -1;
48static char group_dir[PATH_MAX];
49static char group_file[PATH_MAX];
50static char tempname[PATH_MAX];
51static int initialized;
52
53/*
54 * Initialize statics
55 */
56int
57gr_init(const char *dir, const char *group)
58{
59
60	if (dir == NULL) {
61		strcpy(group_dir, _PATH_ETC);
62	} else {
63		if (strlen(dir) >= sizeof(group_dir)) {
64			errno = ENAMETOOLONG;
65			return (-1);
66		}
67		strcpy(group_dir, dir);
68	}
69
70	if (group == NULL) {
71		if (dir == NULL) {
72			strcpy(group_file, _PATH_GROUP);
73		} else if (snprintf(group_file, sizeof(group_file), "%s/group",
74			group_dir) > (int)sizeof(group_file)) {
75			errno = ENAMETOOLONG;
76			return (-1);
77		}
78	} else {
79		if (strlen(group) >= sizeof(group_file)) {
80			errno = ENAMETOOLONG;
81			return (-1);
82		}
83		strcpy(group_file, group);
84	}
85
86	initialized = 1;
87	return (0);
88}
89
90/*
91 * Lock the group file
92 */
93int
94gr_lock(void)
95{
96	if (*group_file == '\0')
97		return (-1);
98
99	for (;;) {
100		struct stat st;
101
102		lockfd = flopen(group_file, O_RDONLY|O_NONBLOCK|O_CLOEXEC, 0);
103		if (lockfd == -1) {
104			if (errno == EWOULDBLOCK) {
105				errx(1, "the group file is busy");
106			} else {
107				err(1, "could not lock the group file: ");
108			}
109		}
110		if (fstat(lockfd, &st) == -1)
111			err(1, "fstat() failed: ");
112		if (st.st_nlink != 0)
113			break;
114		close(lockfd);
115		lockfd = -1;
116	}
117	return (lockfd);
118}
119
120/*
121 * Create and open a presmuably safe temp file for editing group data
122 */
123int
124gr_tmp(int mfd)
125{
126	char buf[8192];
127	ssize_t nr;
128	const char *p;
129	int tfd;
130
131	if (*group_file == '\0')
132		return (-1);
133	if ((p = strrchr(group_file, '/')))
134		++p;
135	else
136		p = group_file;
137	if (snprintf(tempname, sizeof(tempname), "%.*sgroup.XXXXXX",
138		(int)(p - group_file), group_file) >= (int)sizeof(tempname)) {
139		errno = ENAMETOOLONG;
140		return (-1);
141	}
142	if ((tfd = mkstemp(tempname)) == -1)
143		return (-1);
144	if (mfd != -1) {
145		while ((nr = read(mfd, buf, sizeof(buf))) > 0)
146			if (write(tfd, buf, (size_t)nr) != nr)
147				break;
148		if (nr != 0) {
149			unlink(tempname);
150			*tempname = '\0';
151			close(tfd);
152			return (-1);
153		}
154	}
155	return (tfd);
156}
157
158/*
159 * Copy the group file from one descriptor to another, replacing, deleting
160 * or adding a single record on the way.
161 */
162int
163gr_copy(int ffd, int tfd, const struct group *gr, struct group *old_gr)
164{
165	char buf[8192], *end, *line, *p, *q, *r, t;
166	struct group *fgr;
167	const struct group *sgr;
168	size_t len;
169	int eof, readlen;
170
171	sgr = gr;
172	if (gr == NULL) {
173		line = NULL;
174		if (old_gr == NULL)
175			return (-1);
176		sgr = old_gr;
177	} else if ((line = gr_make(gr)) == NULL)
178		return (-1);
179
180	eof = 0;
181	len = 0;
182	p = q = end = buf;
183	for (;;) {
184		/* find the end of the current line */
185		for (p = q; q < end && *q != '\0'; ++q)
186			if (*q == '\n')
187				break;
188
189		/* if we don't have a complete line, fill up the buffer */
190		if (q >= end) {
191			if (eof)
192				break;
193			if ((size_t)(q - p) >= sizeof(buf)) {
194				warnx("group line too long");
195				errno = EINVAL; /* hack */
196				goto err;
197			}
198			if (p < end) {
199				q = memmove(buf, p, end -p);
200				end -= p - buf;
201			} else {
202				p = q = end = buf;
203			}
204			readlen = read(ffd, end, sizeof(buf) - (end -buf));
205			if (readlen == -1)
206				goto err;
207			else
208				len = (size_t)readlen;
209			if (len == 0 && p == buf)
210				break;
211			end += len;
212			len = end - buf;
213			if (len < (ssize_t)sizeof(buf)) {
214				eof = 1;
215				if (len > 0 && buf[len -1] != '\n')
216					++len, *end++ = '\n';
217			}
218			continue;
219		}
220
221		/* is it a blank line or a comment? */
222		for (r = p; r < q && isspace(*r); ++r)
223			/* nothing */;
224		if (r == q || *r == '#') {
225			/* yep */
226			if (write(tfd, p, q -p + 1) != q - p + 1)
227				goto err;
228			++q;
229			continue;
230		}
231
232		/* is it the one we're looking for? */
233
234		t = *q;
235		*q = '\0';
236
237		fgr = gr_scan(r);
238
239		/* fgr is either a struct group for the current line,
240		 * or NULL if the line is malformed.
241		 */
242
243		*q = t;
244		if (fgr == NULL || fgr->gr_gid != sgr->gr_gid) {
245			/* nope */
246			if (fgr != NULL)
247				free(fgr);
248			if (write(tfd, p, q - p + 1) != q - p + 1)
249				goto err;
250			++q;
251			continue;
252		}
253		if (old_gr && !gr_equal(fgr, old_gr)) {
254			warnx("entry inconsistent");
255			free(fgr);
256			errno = EINVAL; /* hack */
257			goto err;
258		}
259		free(fgr);
260
261		/* it is, replace or remove it */
262		if (line != NULL) {
263			len = strlen(line);
264			if (write(tfd, line, len) != (int) len)
265				goto err;
266		} else {
267			/* when removed, avoid the \n */
268			q++;
269		}
270		/* we're done, just copy the rest over */
271		for (;;) {
272			if (write(tfd, q, end - q) != end - q)
273				goto err;
274			q = buf;
275			readlen = read(ffd, buf, sizeof(buf));
276			if (readlen == 0)
277				break;
278			else
279				len = (size_t)readlen;
280			if (readlen == -1)
281				goto err;
282			end = buf + len;
283		}
284		goto done;
285	}
286
287	/* if we got here, we didn't find the old entry */
288	if (line == NULL) {
289		errno = ENOENT;
290		goto err;
291	}
292	len = strlen(line);
293	if ((size_t)write(tfd, line, len) != len ||
294	   write(tfd, "\n", 1) != 1)
295		goto err;
296 done:
297	if (line != NULL)
298		free(line);
299	return (0);
300 err:
301	if (line != NULL)
302		free(line);
303	return (-1);
304}
305
306/*
307 * Regenerate the group file
308 */
309int
310gr_mkdb(void)
311{
312	if (chmod(tempname, 0644) != 0)
313		return (-1);
314
315	return (rename(tempname, group_file));
316}
317
318/*
319 * Clean up. Preserver errno for the caller's convenience.
320 */
321void
322gr_fini(void)
323{
324	int serrno;
325
326	if (!initialized)
327		return;
328	initialized = 0;
329	serrno = errno;
330	if (*tempname != '\0') {
331		unlink(tempname);
332		*tempname = '\0';
333	}
334	if (lockfd != -1)
335		close(lockfd);
336	errno = serrno;
337}
338
339/*
340 * Compares two struct group's.
341 */
342int
343gr_equal(const struct group *gr1, const struct group *gr2)
344{
345	int gr1_ndx;
346	int gr2_ndx;
347
348	/* Check that the non-member information is the same. */
349	if (gr1->gr_name == NULL || gr2->gr_name == NULL) {
350		if (gr1->gr_name != gr2->gr_name)
351			return (false);
352	} else if (strcmp(gr1->gr_name, gr2->gr_name) != 0)
353		return (false);
354	if (gr1->gr_passwd == NULL || gr2->gr_passwd == NULL) {
355		if (gr1->gr_passwd != gr2->gr_passwd)
356			return (false);
357	} else if (strcmp(gr1->gr_passwd, gr2->gr_passwd) != 0)
358		return (false);
359	if (gr1->gr_gid != gr2->gr_gid)
360		return (false);
361
362	/* Check all members in both groups. */
363	if (gr1->gr_mem == NULL || gr2->gr_mem == NULL) {
364		if (gr1->gr_mem != gr2->gr_mem)
365			return (false);
366	} else {
367		for (gr1_ndx = 0; gr1->gr_mem[gr1_ndx] != NULL; gr1_ndx++) {
368			for (gr2_ndx = 0;; gr2_ndx++) {
369				if (gr2->gr_mem[gr2_ndx] == NULL)
370					return (false);
371				if (strcmp(gr1->gr_mem[gr1_ndx],
372				    gr2->gr_mem[gr2_ndx]) == 0) {
373					break;
374				}
375			}
376		}
377
378		/* Check that group2 does not have more members than group1. */
379		if (gr2->gr_mem[gr1_ndx] != NULL)
380			return (false);
381	}
382
383	return (true);
384}
385
386/*
387 * Make a group line out of a struct group.
388 */
389char *
390gr_make(const struct group *gr)
391{
392	const char *group_line_format = "%s:%s:%ju:";
393	char *line;
394	size_t line_size;
395	int ndx;
396
397	/* Calculate the length of the group line. */
398	line_size = snprintf(NULL, 0, group_line_format, gr->gr_name,
399	    gr->gr_passwd, (uintmax_t)gr->gr_gid) + 1;
400	if (gr->gr_mem != NULL) {
401		for (ndx = 0; gr->gr_mem[ndx] != NULL; ndx++)
402			line_size += strlen(gr->gr_mem[ndx]) + 1;
403		if (ndx > 0)
404			line_size--;
405	}
406
407	/* Create the group line and fill it. */
408	if ((line = malloc(line_size)) == NULL)
409		return (NULL);
410	snprintf(line, line_size, group_line_format, gr->gr_name, gr->gr_passwd,
411	    (uintmax_t)gr->gr_gid);
412	if (gr->gr_mem != NULL)
413		for (ndx = 0; gr->gr_mem[ndx] != NULL; ndx++) {
414			strcat(line, gr->gr_mem[ndx]);
415			if (gr->gr_mem[ndx + 1] != NULL)
416				strcat(line, ",");
417		}
418
419	return (line);
420}
421
422/*
423 * Duplicate a struct group.
424 */
425struct group *
426gr_dup(const struct group *gr)
427{
428	struct group *newgr;
429	char *dst;
430	size_t len;
431	int ndx;
432	int num_mem;
433
434	/* Calculate size of the group. */
435	len = sizeof(*newgr);
436	if (gr->gr_name != NULL)
437		len += strlen(gr->gr_name) + 1;
438	if (gr->gr_passwd != NULL)
439		len += strlen(gr->gr_passwd) + 1;
440	if (gr->gr_mem != NULL) {
441		for (num_mem = 0; gr->gr_mem[num_mem] != NULL; num_mem++)
442			len += strlen(gr->gr_mem[num_mem]) + 1;
443		len += (num_mem + 1) * sizeof(*gr->gr_mem);
444	} else
445		num_mem = -1;
446	/* Create new group and copy old group into it. */
447	if ((newgr = malloc(len)) == NULL)
448		return (NULL);
449	/* point new gr_mem to end of struct + 1 */
450	if (gr->gr_mem != NULL)
451		newgr->gr_mem = (char **)(newgr + 1);
452	else
453		newgr->gr_mem = NULL;
454	/* point dst after the end of all the gr_mem pointers in newgr */
455	dst = (char *)&newgr->gr_mem[num_mem + 1];
456	if (gr->gr_name != NULL) {
457		newgr->gr_name = dst;
458		dst = stpcpy(dst, gr->gr_name) + 1;
459	} else {
460		newgr->gr_name = NULL;
461	}
462	if (gr->gr_passwd != NULL) {
463		newgr->gr_passwd = dst;
464		dst = stpcpy(dst, gr->gr_passwd) + 1;
465	} else {
466		newgr->gr_passwd = NULL;
467	}
468	newgr->gr_gid = gr->gr_gid;
469	if (gr->gr_mem != NULL) {
470		for (ndx = 0; ndx < num_mem; ndx++) {
471			newgr->gr_mem[ndx] = dst;
472			dst = stpcpy(dst, gr->gr_mem[ndx]) + 1;
473		}
474		newgr->gr_mem[ndx] = NULL;
475	}
476	return (newgr);
477}
478
479/*
480 * Add a new member name to a struct group.
481 */
482struct group *
483gr_add(struct group *gr, char *newmember)
484{
485	size_t mlen;
486	int num_mem=0;
487	char **members;
488	struct group *newgr;
489
490	if (newmember == NULL)
491		return(gr_dup(gr));
492
493	if (gr->gr_mem != NULL) {
494		for (num_mem = 0; gr->gr_mem[num_mem] != NULL; num_mem++) {
495			if (strcmp(gr->gr_mem[num_mem], newmember) == 0) {
496				errno = EEXIST;
497				return (NULL);
498			}
499		}
500	}
501	/* Allocate enough for current pointers + 1 more and NULL marker */
502	mlen = (num_mem + 2) * sizeof(*gr->gr_mem);
503	if ((members = malloc(mlen)) == NULL)
504		return (NULL);
505	memcpy(members, gr->gr_mem, num_mem * sizeof(*gr->gr_mem));
506	members[num_mem++] = newmember;
507	members[num_mem] = NULL;
508	gr->gr_mem = members;
509	newgr = gr_dup(gr);
510	free(members);
511	return (newgr);
512}
513
514/*
515 * Scan a line and place it into a group structure.
516 */
517static bool
518__gr_scan(char *line, struct group *gr)
519{
520	char *loc;
521	int ndx;
522
523	/* Assign non-member information to structure. */
524	gr->gr_name = line;
525	if ((loc = strchr(line, ':')) == NULL)
526		return (false);
527	*loc = '\0';
528	gr->gr_passwd = loc + 1;
529	if (*gr->gr_passwd == ':')
530		*gr->gr_passwd = '\0';
531	else {
532		if ((loc = strchr(loc + 1, ':')) == NULL)
533			return (false);
534		*loc = '\0';
535	}
536	if (sscanf(loc + 1, "%u", &gr->gr_gid) != 1)
537		return (false);
538
539	/* Assign member information to structure. */
540	if ((loc = strchr(loc + 1, ':')) == NULL)
541		return (false);
542	line = loc + 1;
543	gr->gr_mem = NULL;
544	ndx = 0;
545	do {
546		gr->gr_mem = reallocf(gr->gr_mem, sizeof(*gr->gr_mem) *
547		    (ndx + 1));
548		if (gr->gr_mem == NULL)
549			return (false);
550
551		/* Skip locations without members (i.e., empty string). */
552		do {
553			gr->gr_mem[ndx] = strsep(&line, ",");
554		} while (gr->gr_mem[ndx] != NULL && *gr->gr_mem[ndx] == '\0');
555	} while (gr->gr_mem[ndx++] != NULL);
556
557	return (true);
558}
559
560/*
561 * Create a struct group from a line.
562 */
563struct group *
564gr_scan(const char *line)
565{
566	struct group gr;
567	char *line_copy;
568	struct group *new_gr;
569
570	if ((line_copy = strdup(line)) == NULL)
571		return (NULL);
572	if (!__gr_scan(line_copy, &gr)) {
573		free(line_copy);
574		return (NULL);
575	}
576	new_gr = gr_dup(&gr);
577	free(line_copy);
578	if (gr.gr_mem != NULL)
579		free(gr.gr_mem);
580
581	return (new_gr);
582}
583