1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1988, 1993, 1994
5 *	The Regents of the University of California.  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 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/param.h>
33#include <sys/stat.h>
34
35#include <err.h>
36#include <errno.h>
37#include <fcntl.h>
38#include <fts.h>
39#include <grp.h>
40#include <libgen.h>
41#include <pwd.h>
42#include <signal.h>
43#include <stddef.h>
44#include <stdint.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <unistd.h>
49
50static void	a_gid(const char *);
51static void	a_uid(const char *);
52static void	chownerr(const char *);
53static uid_t	id(const char *, const char *);
54static void	usage(void);
55static void	print_info(const FTSENT *, int);
56
57static uid_t uid;
58static gid_t gid;
59static int ischown;
60static const char *gname;
61static volatile sig_atomic_t siginfo;
62
63static void
64siginfo_handler(int sig __unused)
65{
66
67	siginfo = 1;
68}
69
70int
71main(int argc, char **argv)
72{
73	FTS *ftsp;
74	FTSENT *p;
75	int Hflag, Lflag, Rflag, fflag, hflag, vflag, xflag;
76	int ch, fts_options, rval;
77	char *cp;
78
79	ischown = (strcmp(basename(argv[0]), "chown") == 0);
80
81	Hflag = Lflag = Rflag = fflag = hflag = vflag = xflag = 0;
82	while ((ch = getopt(argc, argv, "HLPRfhvx")) != -1)
83		switch (ch) {
84		case 'H':
85			Hflag = 1;
86			Lflag = 0;
87			break;
88		case 'L':
89			Lflag = 1;
90			Hflag = 0;
91			break;
92		case 'P':
93			Hflag = Lflag = 0;
94			break;
95		case 'R':
96			Rflag = 1;
97			break;
98		case 'f':
99			fflag = 1;
100			break;
101		case 'h':
102			hflag = 1;
103			break;
104		case 'v':
105			vflag++;
106			break;
107		case 'x':
108			xflag = 1;
109			break;
110		case '?':
111		default:
112			usage();
113		}
114	argv += optind;
115	argc -= optind;
116
117	if (argc < 2)
118		usage();
119
120	(void)signal(SIGINFO, siginfo_handler);
121
122	if (Rflag) {
123		if (hflag && (Hflag || Lflag))
124			errx(1, "the -R%c and -h options may not be "
125			    "specified together", Hflag ? 'H' : 'L');
126		if (Lflag) {
127			fts_options = FTS_LOGICAL;
128		} else {
129			fts_options = FTS_PHYSICAL;
130
131			if (Hflag) {
132				fts_options |= FTS_COMFOLLOW;
133			}
134		}
135	} else if (hflag) {
136		fts_options = FTS_PHYSICAL;
137	} else {
138		fts_options = FTS_LOGICAL;
139	}
140
141	if (xflag)
142		fts_options |= FTS_XDEV;
143
144	uid = (uid_t)-1;
145	gid = (gid_t)-1;
146	if (ischown) {
147		if ((cp = strchr(*argv, ':')) != NULL) {
148			*cp++ = '\0';
149			a_gid(cp);
150		}
151#ifdef SUPPORT_DOT
152		else if ((cp = strchr(*argv, '.')) != NULL) {
153			warnx("separation of user and group with a period is deprecated");
154			*cp++ = '\0';
155			a_gid(cp);
156		}
157#endif
158		a_uid(*argv);
159	} else
160		a_gid(*argv);
161
162	if ((ftsp = fts_open(++argv, fts_options, NULL)) == NULL)
163		err(1, NULL);
164
165	for (rval = 0; errno = 0, (p = fts_read(ftsp)) != NULL;) {
166		int atflag;
167
168		if ((fts_options & FTS_LOGICAL) ||
169		    ((fts_options & FTS_COMFOLLOW) &&
170		    p->fts_level == FTS_ROOTLEVEL))
171			atflag = 0;
172		else
173			atflag = AT_SYMLINK_NOFOLLOW;
174
175		switch (p->fts_info) {
176		case FTS_D:			/* Change it at FTS_DP. */
177			if (!Rflag)
178				fts_set(ftsp, p, FTS_SKIP);
179			continue;
180		case FTS_DNR:			/* Warn, chown. */
181			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
182			rval = 1;
183			break;
184		case FTS_ERR:			/* Warn, continue. */
185		case FTS_NS:
186			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
187			rval = 1;
188			continue;
189		default:
190			break;
191		}
192		if (siginfo) {
193			print_info(p, 2);
194			siginfo = 0;
195		}
196		if ((uid == (uid_t)-1 || uid == p->fts_statp->st_uid) &&
197		    (gid == (gid_t)-1 || gid == p->fts_statp->st_gid))
198			continue;
199		if (fchownat(AT_FDCWD, p->fts_accpath, uid, gid, atflag)
200		    == -1 && !fflag) {
201			chownerr(p->fts_path);
202			rval = 1;
203		} else if (vflag)
204			print_info(p, vflag);
205	}
206	if (errno)
207		err(1, "fts_read");
208	exit(rval);
209}
210
211static void
212a_gid(const char *s)
213{
214	struct group *gr;
215
216	if (*s == '\0')			/* Argument was "uid[:.]". */
217		return;
218	gname = s;
219	gid = ((gr = getgrnam(s)) != NULL) ? gr->gr_gid : id(s, "group");
220}
221
222static void
223a_uid(const char *s)
224{
225	struct passwd *pw;
226
227	if (*s == '\0')			/* Argument was "[:.]gid". */
228		return;
229	uid = ((pw = getpwnam(s)) != NULL) ? pw->pw_uid : id(s, "user");
230}
231
232static uid_t
233id(const char *name, const char *type)
234{
235	unsigned long val;
236	char *ep;
237
238	errno = 0;
239	val = strtoul(name, &ep, 10);
240	_Static_assert(UID_MAX >= GID_MAX, "UID MAX less than GID MAX");
241	if (errno || *ep != '\0' || val > UID_MAX)
242		errx(1, "%s: illegal %s name", name, type);
243	return (val);
244}
245
246static void
247chownerr(const char *file)
248{
249	static uid_t euid = -1;
250	static int ngroups = -1;
251	static long ngroups_max;
252	gid_t *groups;
253
254	/* Check for chown without being root. */
255	if (errno != EPERM || (uid != (uid_t)-1 &&
256	    euid == (uid_t)-1 && (euid = geteuid()) != 0)) {
257		warn("%s", file);
258		return;
259	}
260
261	/* Check group membership; kernel just returns EPERM. */
262	if (gid != (gid_t)-1 && ngroups == -1 &&
263	    euid == (uid_t)-1 && (euid = geteuid()) != 0) {
264		ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
265		if ((groups = malloc(sizeof(gid_t) * ngroups_max)) == NULL)
266			err(1, "malloc");
267		ngroups = getgroups(ngroups_max, groups);
268		while (--ngroups >= 0 && gid != groups[ngroups]);
269		free(groups);
270		if (ngroups < 0) {
271			warnx("you are not a member of group %s", gname);
272			return;
273		}
274	}
275	warn("%s", file);
276}
277
278static void
279usage(void)
280{
281
282	if (ischown)
283		(void)fprintf(stderr, "%s\n%s\n",
284		    "usage: chown [-fhvx] [-R [-H | -L | -P]] owner[:group]"
285		    " file ...",
286		    "       chown [-fhvx] [-R [-H | -L | -P]] :group file ...");
287	else
288		(void)fprintf(stderr, "%s\n",
289		    "usage: chgrp [-fhvx] [-R [-H | -L | -P]] group file ...");
290	exit(1);
291}
292
293static void
294print_info(const FTSENT *p, int vflag)
295{
296
297	printf("%s", p->fts_path);
298	if (vflag > 1) {
299		if (ischown) {
300			printf(": %ju:%ju -> %ju:%ju",
301			    (uintmax_t)p->fts_statp->st_uid,
302			    (uintmax_t)p->fts_statp->st_gid,
303			    (uid == (uid_t)-1) ?
304			    (uintmax_t)p->fts_statp->st_uid : (uintmax_t)uid,
305			    (gid == (gid_t)-1) ?
306			    (uintmax_t)p->fts_statp->st_gid : (uintmax_t)gid);
307		} else {
308			printf(": %ju -> %ju", (uintmax_t)p->fts_statp->st_gid,
309			    (gid == (gid_t)-1) ?
310			    (uintmax_t)p->fts_statp->st_gid : (uintmax_t)gid);
311		}
312	}
313	printf("\n");
314}
315