xref: /freebsd/lib/libutil/gr_util.c (revision 3c91c65a2b999a8d27e99bcc6493de7cf812c948)
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$");
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 
47 static int lockfd = -1;
48 static char group_dir[PATH_MAX];
49 static char group_file[PATH_MAX];
50 static char tempname[PATH_MAX];
51 static int initialized;
52 
53 /*
54  * Initialize statics
55  */
56 int
57 gr_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  */
93 int
94 gr_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  */
123 int
124 gr_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  */
162 int
163 gr_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  */
309 int
310 gr_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. Preserves errno for the caller's convenience.
320  */
321 void
322 gr_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  */
342 int
343 gr_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  */
389 char *
390 gr_make(const struct group *gr)
391 {
392 	const char *group_line_format = "%s:%s:%ju:";
393 	const char *sep;
394 	char *line;
395 	char *p;
396 	size_t line_size;
397 	int ndx;
398 
399 	/* Calculate the length of the group line. */
400 	line_size = snprintf(NULL, 0, group_line_format, gr->gr_name,
401 	    gr->gr_passwd, (uintmax_t)gr->gr_gid) + 1;
402 	if (gr->gr_mem != NULL) {
403 		for (ndx = 0; gr->gr_mem[ndx] != NULL; ndx++)
404 			line_size += strlen(gr->gr_mem[ndx]) + 1;
405 		if (ndx > 0)
406 			line_size--;
407 	}
408 
409 	/* Create the group line and fill it. */
410 	if ((line = p = malloc(line_size)) == NULL)
411 		return (NULL);
412 	p += sprintf(p, group_line_format, gr->gr_name, gr->gr_passwd,
413 	    (uintmax_t)gr->gr_gid);
414 	if (gr->gr_mem != NULL) {
415 		sep = "";
416 		for (ndx = 0; gr->gr_mem[ndx] != NULL; ndx++) {
417 			p = stpcpy(p, sep);
418 			p = stpcpy(p, gr->gr_mem[ndx]);
419 			sep = ",";
420 		}
421 	}
422 
423 	return (line);
424 }
425 
426 /*
427  * Duplicate a struct group.
428  */
429 struct group *
430 gr_dup(const struct group *gr)
431 {
432 	struct group *newgr;
433 	char *dst;
434 	size_t len;
435 	int ndx;
436 	int num_mem;
437 
438 	/* Calculate size of the group. */
439 	len = sizeof(*newgr);
440 	if (gr->gr_name != NULL)
441 		len += strlen(gr->gr_name) + 1;
442 	if (gr->gr_passwd != NULL)
443 		len += strlen(gr->gr_passwd) + 1;
444 	if (gr->gr_mem != NULL) {
445 		for (num_mem = 0; gr->gr_mem[num_mem] != NULL; num_mem++)
446 			len += strlen(gr->gr_mem[num_mem]) + 1;
447 		len += (num_mem + 1) * sizeof(*gr->gr_mem);
448 	} else
449 		num_mem = -1;
450 	/* Create new group and copy old group into it. */
451 	if ((newgr = malloc(len)) == NULL)
452 		return (NULL);
453 	/* point new gr_mem to end of struct + 1 */
454 	if (gr->gr_mem != NULL)
455 		newgr->gr_mem = (char **)(newgr + 1);
456 	else
457 		newgr->gr_mem = NULL;
458 	/* point dst after the end of all the gr_mem pointers in newgr */
459 	dst = (char *)&newgr->gr_mem[num_mem + 1];
460 	if (gr->gr_name != NULL) {
461 		newgr->gr_name = dst;
462 		dst = stpcpy(dst, gr->gr_name) + 1;
463 	} else {
464 		newgr->gr_name = NULL;
465 	}
466 	if (gr->gr_passwd != NULL) {
467 		newgr->gr_passwd = dst;
468 		dst = stpcpy(dst, gr->gr_passwd) + 1;
469 	} else {
470 		newgr->gr_passwd = NULL;
471 	}
472 	newgr->gr_gid = gr->gr_gid;
473 	if (gr->gr_mem != NULL) {
474 		for (ndx = 0; ndx < num_mem; ndx++) {
475 			newgr->gr_mem[ndx] = dst;
476 			dst = stpcpy(dst, gr->gr_mem[ndx]) + 1;
477 		}
478 		newgr->gr_mem[ndx] = NULL;
479 	}
480 	return (newgr);
481 }
482 
483 /*
484  * Add a new member name to a struct group.
485  */
486 struct group *
487 gr_add(struct group *gr, char *newmember)
488 {
489 	size_t mlen;
490 	int num_mem=0;
491 	char **members;
492 	struct group *newgr;
493 
494 	if (newmember == NULL)
495 		return(gr_dup(gr));
496 
497 	if (gr->gr_mem != NULL) {
498 		for (num_mem = 0; gr->gr_mem[num_mem] != NULL; num_mem++) {
499 			if (strcmp(gr->gr_mem[num_mem], newmember) == 0) {
500 				errno = EEXIST;
501 				return (NULL);
502 			}
503 		}
504 	}
505 	/* Allocate enough for current pointers + 1 more and NULL marker */
506 	mlen = (num_mem + 2) * sizeof(*gr->gr_mem);
507 	if ((members = malloc(mlen)) == NULL)
508 		return (NULL);
509 	memcpy(members, gr->gr_mem, num_mem * sizeof(*gr->gr_mem));
510 	members[num_mem++] = newmember;
511 	members[num_mem] = NULL;
512 	gr->gr_mem = members;
513 	newgr = gr_dup(gr);
514 	free(members);
515 	return (newgr);
516 }
517 
518 /*
519  * Scan a line and place it into a group structure.
520  */
521 static bool
522 __gr_scan(char *line, struct group *gr)
523 {
524 	char *loc;
525 	int ndx;
526 
527 	/* Assign non-member information to structure. */
528 	gr->gr_name = line;
529 	if ((loc = strchr(line, ':')) == NULL)
530 		return (false);
531 	*loc = '\0';
532 	gr->gr_passwd = loc + 1;
533 	if (*gr->gr_passwd == ':')
534 		*gr->gr_passwd = '\0';
535 	else {
536 		if ((loc = strchr(loc + 1, ':')) == NULL)
537 			return (false);
538 		*loc = '\0';
539 	}
540 	if (sscanf(loc + 1, "%u", &gr->gr_gid) != 1)
541 		return (false);
542 
543 	/* Assign member information to structure. */
544 	if ((loc = strchr(loc + 1, ':')) == NULL)
545 		return (false);
546 	line = loc + 1;
547 	gr->gr_mem = NULL;
548 	ndx = 0;
549 	do {
550 		gr->gr_mem = reallocf(gr->gr_mem, sizeof(*gr->gr_mem) *
551 		    (ndx + 1));
552 		if (gr->gr_mem == NULL)
553 			return (false);
554 
555 		/* Skip locations without members (i.e., empty string). */
556 		do {
557 			gr->gr_mem[ndx] = strsep(&line, ",");
558 		} while (gr->gr_mem[ndx] != NULL && *gr->gr_mem[ndx] == '\0');
559 	} while (gr->gr_mem[ndx++] != NULL);
560 
561 	return (true);
562 }
563 
564 /*
565  * Create a struct group from a line.
566  */
567 struct group *
568 gr_scan(const char *line)
569 {
570 	struct group gr;
571 	char *line_copy;
572 	struct group *new_gr;
573 
574 	if ((line_copy = strdup(line)) == NULL)
575 		return (NULL);
576 	if (!__gr_scan(line_copy, &gr)) {
577 		free(line_copy);
578 		return (NULL);
579 	}
580 	new_gr = gr_dup(&gr);
581 	free(line_copy);
582 	if (gr.gr_mem != NULL)
583 		free(gr.gr_mem);
584 
585 	return (new_gr);
586 }
587