1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (C) 1996
5 *	David L. Nugent.  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 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#ifndef lint
30static const char rcsid[] =
31  "$FreeBSD: stable/11/usr.sbin/pw/grupd.c 330449 2018-03-05 07:26:05Z eadler $";
32#endif /* not lint */
33
34#include <err.h>
35#include <grp.h>
36#include <libutil.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <unistd.h>
40
41#include "pwupd.h"
42
43char *
44getgrpath(const char * file)
45{
46	static char pathbuf[MAXPATHLEN];
47
48	snprintf(pathbuf, sizeof pathbuf, "%s/%s", conf.etcpath, file);
49
50	return (pathbuf);
51}
52
53static int
54gr_update(struct group * grp, char const * group)
55{
56	int pfd, tfd;
57	struct group *gr = NULL;
58	struct group *old_gr = NULL;
59
60	if (grp != NULL)
61		gr = gr_dup(grp);
62
63	if (group != NULL)
64		old_gr = GETGRNAM(group);
65
66	if (gr_init(conf.etcpath, NULL))
67		err(1, "gr_init()");
68
69	if ((pfd = gr_lock()) == -1) {
70		gr_fini();
71		err(1, "gr_lock()");
72	}
73	if ((tfd = gr_tmp(-1)) == -1) {
74		gr_fini();
75		err(1, "gr_tmp()");
76	}
77	if (gr_copy(pfd, tfd, gr, old_gr) == -1) {
78		gr_fini();
79		close(tfd);
80		err(1, "gr_copy()");
81	}
82	fsync(tfd);
83	close(tfd);
84	if (gr_mkdb() == -1) {
85		gr_fini();
86		err(1, "gr_mkdb()");
87	}
88	free(gr);
89	gr_fini();
90	return 0;
91}
92
93
94int
95addgrent(struct group * grp)
96{
97	return gr_update(grp, NULL);
98}
99
100int
101chggrent(char const * login, struct group * grp)
102{
103	return gr_update(grp, login);
104}
105
106int
107delgrent(struct group * grp)
108{
109
110	return (gr_update(NULL, grp->gr_name));
111}
112