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