1/*	$NetBSD: setmode.c,v 1.38 2022/04/19 20:32:15 rillig Exp $	*/
2
3/*
4 * Copyright (c) 1989, 1993, 1994
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Dave Borman at Cray Research, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include <sys/cdefs.h>
36#if defined(LIBC_SCCS) && !defined(lint)
37#if 0
38static char sccsid[] = "@(#)setmode.c	8.2 (Berkeley) 3/25/94";
39#else
40__RCSID("$NetBSD: setmode.c,v 1.38 2022/04/19 20:32:15 rillig Exp $");
41#endif
42#endif /* LIBC_SCCS and not lint */
43
44#include "namespace.h"
45#include <sys/types.h>
46#include <sys/stat.h>
47
48#include <assert.h>
49#include <ctype.h>
50#include <errno.h>
51#include <signal.h>
52#include <stdlib.h>
53#include <limits.h>
54#include <unistd.h>
55
56#ifdef SETMODE_DEBUG
57#include <stdio.h>
58#endif
59
60#ifdef __weak_alias
61__weak_alias(getmode,_getmode)
62__weak_alias(setmode,_setmode)
63#endif
64
65#define	SET_LEN	6		/* initial # of bitcmd struct to malloc */
66#define	SET_LEN_INCR 4		/* # of bitcmd structs to add as needed */
67
68typedef struct bitcmd {
69	char	cmd;
70	char	cmd2;
71	mode_t	bits;
72} BITCMD;
73
74#define	CMD2_CLR	0x01
75#define	CMD2_SET	0x02
76#define	CMD2_GBITS	0x04
77#define	CMD2_OBITS	0x08
78#define	CMD2_UBITS	0x10
79
80static BITCMD	*addcmd(BITCMD *, mode_t, mode_t, mode_t, mode_t);
81static void	 compress_mode(BITCMD *);
82#ifdef SETMODE_DEBUG
83static void	 dumpmode(BITCMD *);
84#endif
85
86/*
87 * Given the old mode and an array of bitcmd structures, apply the operations
88 * described in the bitcmd structures to the old mode, and return the new mode.
89 * Note that there is no '=' command; a strict assignment is just a '-' (clear
90 * bits) followed by a '+' (set bits).
91 */
92mode_t
93getmode(const void *bbox, mode_t omode)
94{
95	const BITCMD *set;
96	mode_t clrval, newmode, value;
97
98	_DIAGASSERT(bbox != NULL);
99
100	set = (const BITCMD *)bbox;
101	newmode = omode;
102	for (value = 0;; set++)
103		switch(set->cmd) {
104		/*
105		 * When copying the user, group or other bits around, we "know"
106		 * where the bits are in the mode so that we can do shifts to
107		 * copy them around.  If we don't use shifts, it gets real
108		 * grundgy with lots of single bit checks and bit sets.
109		 */
110		case 'u':
111			value = (newmode & S_IRWXU) >> 6;
112			goto common;
113
114		case 'g':
115			value = (newmode & S_IRWXG) >> 3;
116			goto common;
117
118		case 'o':
119			value = newmode & S_IRWXO;
120common:			if (set->cmd2 & CMD2_CLR) {
121				clrval =
122				    (set->cmd2 & CMD2_SET) ?  S_IRWXO : value;
123				if (set->cmd2 & CMD2_UBITS)
124					newmode &= ~((clrval<<6) & set->bits);
125				if (set->cmd2 & CMD2_GBITS)
126					newmode &= ~((clrval<<3) & set->bits);
127				if (set->cmd2 & CMD2_OBITS)
128					newmode &= ~(clrval & set->bits);
129			}
130			if (set->cmd2 & CMD2_SET) {
131				if (set->cmd2 & CMD2_UBITS)
132					newmode |= (value<<6) & set->bits;
133				if (set->cmd2 & CMD2_GBITS)
134					newmode |= (value<<3) & set->bits;
135				if (set->cmd2 & CMD2_OBITS)
136					newmode |= value & set->bits;
137			}
138			break;
139
140		case '+':
141			newmode |= set->bits;
142			break;
143
144		case '-':
145			newmode &= ~set->bits;
146			break;
147
148		case 'X':
149			if (omode & (S_IFDIR|S_IXUSR|S_IXGRP|S_IXOTH))
150				newmode |= set->bits;
151			break;
152
153		case '\0':
154		default:
155#ifdef SETMODE_DEBUG
156			(void)printf("getmode:%04o -> %04o\n", omode, newmode);
157#endif
158			return (newmode);
159		}
160}
161
162#define	ADDCMD(a, b, c, d) do {						\
163	if (set >= endset) {						\
164		BITCMD *newset;						\
165		setlen += SET_LEN_INCR;					\
166		newset = saveset;					\
167		errno = reallocarr(&newset, setlen, sizeof(*newset));	\
168		if (errno)						\
169			goto out;					\
170		set = newset + (set - saveset);				\
171		saveset = newset;					\
172		endset = newset + (setlen - 2);				\
173	}								\
174	set = addcmd(set, (mode_t)(a), (mode_t)(b), (mode_t)(c), (d));	\
175} while (0)
176
177#define	STANDARD_BITS	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
178
179void *
180setmode(const char *p)
181{
182	int serrno;
183	char op, *ep;
184	BITCMD *set, *saveset, *endset;
185	sigset_t signset, sigoset;
186	mode_t mask, perm, permXbits, who;
187	long lval;
188	int equalopdone = 0;	/* pacify gcc */
189	int setlen;
190
191	if (!*p) {
192		errno = EINVAL;
193		return NULL;
194	}
195
196	/*
197	 * Get a copy of the mask for the permissions that are mask relative.
198	 * Flip the bits, we want what's not set.  Since it's possible that
199	 * the caller is opening files inside a signal handler, protect them
200	 * as best we can.
201	 */
202	sigfillset(&signset);
203	(void)sigprocmask(SIG_BLOCK, &signset, &sigoset);
204	(void)umask(mask = umask(0));
205	mask = ~mask;
206	(void)sigprocmask(SIG_SETMASK, &sigoset, NULL);
207
208	setlen = SET_LEN + 2;
209	set = NULL;
210	errno = reallocarr(&set, setlen, sizeof(*set));
211	if (errno)
212		return NULL;
213	saveset = set;
214	endset = set + (setlen - 2);
215
216	/*
217	 * If an absolute number, get it and return; disallow non-octal digits
218	 * or illegal bits.
219	 */
220	if (isdigit((unsigned char)*p)) {
221		errno = 0;
222		lval = strtol(p, &ep, 8);
223		if (*ep) {
224			errno = EINVAL;
225			goto out;
226		}
227		if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
228			goto out;
229		if (lval & ~(STANDARD_BITS|S_ISTXT)) {
230			errno = EINVAL;
231			goto out;
232		}
233		perm = (mode_t)lval;
234		ADDCMD('=', (STANDARD_BITS|S_ISTXT), perm, mask);
235		set->cmd = 0;
236		return (saveset);
237	}
238
239	/*
240	 * Build list of structures to set/clear/copy bits as described by
241	 * each clause of the symbolic mode.
242	 */
243	for (;;) {
244		/* First, find out which bits might be modified. */
245		for (who = 0;; ++p) {
246			switch (*p) {
247			case 'a':
248				who |= STANDARD_BITS;
249				break;
250			case 'u':
251				who |= S_ISUID|S_IRWXU;
252				break;
253			case 'g':
254				who |= S_ISGID|S_IRWXG;
255				break;
256			case 'o':
257				who |= S_IRWXO;
258				break;
259			default:
260				goto getop;
261			}
262		}
263
264getop:		if ((op = *p++) != '+' && op != '-' && op != '=') {
265			errno = EINVAL;
266			goto out;
267		}
268		if (op == '=')
269			equalopdone = 0;
270
271		who &= ~S_ISTXT;
272		for (perm = 0, permXbits = 0;; ++p) {
273			switch (*p) {
274			case 'r':
275				perm |= S_IRUSR|S_IRGRP|S_IROTH;
276				break;
277			case 's':
278				/*
279				 * If specific bits where requested and
280				 * only "other" bits ignore set-id.
281				 */
282				if (who == 0 || (who & ~S_IRWXO))
283					perm |= S_ISUID|S_ISGID;
284				break;
285			case 't':
286				/*
287				 * If specific bits where requested and
288				 * only "other" bits ignore set-id.
289				 */
290				if (who == 0 || (who & ~S_IRWXO)) {
291					who |= S_ISTXT;
292					perm |= S_ISTXT;
293				}
294				break;
295			case 'w':
296				perm |= S_IWUSR|S_IWGRP|S_IWOTH;
297				break;
298			case 'X':
299				permXbits = S_IXUSR|S_IXGRP|S_IXOTH;
300				break;
301			case 'x':
302				perm |= S_IXUSR|S_IXGRP|S_IXOTH;
303				break;
304			case 'u':
305			case 'g':
306			case 'o':
307				/*
308				 * When ever we hit 'u', 'g', or 'o', we have
309				 * to flush out any partial mode that we have,
310				 * and then do the copying of the mode bits.
311				 */
312				if (perm) {
313					ADDCMD(op, who, perm, mask);
314					perm = 0;
315				}
316				if (op == '=')
317					equalopdone = 1;
318				if (op == '+' && permXbits) {
319					ADDCMD('X', who, permXbits, mask);
320					permXbits = 0;
321				}
322				ADDCMD(*p, who, op, mask);
323				break;
324
325			default:
326				/*
327				 * Add any permissions that we haven't already
328				 * done.
329				 */
330				if (perm || (op == '=' && !equalopdone)) {
331					if (op == '=')
332						equalopdone = 1;
333					ADDCMD(op, who, perm, mask);
334					perm = 0;
335				}
336				if (permXbits) {
337					ADDCMD('X', who, permXbits, mask);
338					permXbits = 0;
339				}
340				goto apply;
341			}
342		}
343
344apply:		if (!*p)
345			break;
346		if (*p != ',')
347			goto getop;
348		++p;
349	}
350	set->cmd = 0;
351#ifdef SETMODE_DEBUG
352	(void)printf("Before compress_mode()\n");
353	dumpmode(saveset);
354#endif
355	compress_mode(saveset);
356#ifdef SETMODE_DEBUG
357	(void)printf("After compress_mode()\n");
358	dumpmode(saveset);
359#endif
360	return (saveset);
361out:
362	serrno = errno;
363	free(saveset);
364	errno = serrno;
365	return NULL;
366}
367
368static BITCMD *
369addcmd(BITCMD *set, mode_t op, mode_t who, mode_t oparg, mode_t mask)
370{
371
372	_DIAGASSERT(set != NULL);
373
374	switch (op) {
375	case '=':
376		set->cmd = '-';
377		set->bits = who ? who : STANDARD_BITS;
378		set++;
379
380		op = '+';
381		/* FALLTHROUGH */
382	case '+':
383	case '-':
384	case 'X':
385		set->cmd = op;
386		set->bits = (who ? who : mask) & oparg;
387		break;
388
389	case 'u':
390	case 'g':
391	case 'o':
392		set->cmd = op;
393		if (who) {
394			set->cmd2 = ((who & S_IRUSR) ? CMD2_UBITS : 0) |
395				    ((who & S_IRGRP) ? CMD2_GBITS : 0) |
396				    ((who & S_IROTH) ? CMD2_OBITS : 0);
397			set->bits = (mode_t)~0;
398		} else {
399			set->cmd2 = CMD2_UBITS | CMD2_GBITS | CMD2_OBITS;
400			set->bits = mask;
401		}
402
403		if (oparg == '+')
404			set->cmd2 |= CMD2_SET;
405		else if (oparg == '-')
406			set->cmd2 |= CMD2_CLR;
407		else if (oparg == '=')
408			set->cmd2 |= CMD2_SET|CMD2_CLR;
409		break;
410	}
411	return (set + 1);
412}
413
414#ifdef SETMODE_DEBUG
415static void
416dumpmode(BITCMD *set)
417{
418
419	_DIAGASSERT(set != NULL);
420
421	for (; set->cmd; ++set)
422		(void)printf("cmd: '%c' bits %04o%s%s%s%s%s%s\n",
423		    set->cmd, set->bits, set->cmd2 ? " cmd2:" : "",
424		    set->cmd2 & CMD2_CLR ? " CLR" : "",
425		    set->cmd2 & CMD2_SET ? " SET" : "",
426		    set->cmd2 & CMD2_UBITS ? " UBITS" : "",
427		    set->cmd2 & CMD2_GBITS ? " GBITS" : "",
428		    set->cmd2 & CMD2_OBITS ? " OBITS" : "");
429}
430#endif
431
432/*
433 * Given an array of bitcmd structures, compress by compacting consecutive
434 * '+', '-' and 'X' commands into at most 3 commands, one of each.  The 'u',
435 * 'g' and 'o' commands continue to be separate.  They could probably be
436 * compacted, but it's not worth the effort.
437 */
438static void
439compress_mode(BITCMD *set)
440{
441	BITCMD *nset;
442	int setbits, clrbits, Xbits, op;
443
444	_DIAGASSERT(set != NULL);
445
446	for (nset = set;;) {
447		/* Copy over any 'u', 'g' and 'o' commands. */
448		while ((op = nset->cmd) != '+' && op != '-' && op != 'X') {
449			*set++ = *nset++;
450			if (!op)
451				return;
452		}
453
454		for (setbits = clrbits = Xbits = 0;; nset++) {
455			if ((op = nset->cmd) == '-') {
456				clrbits |= nset->bits;
457				setbits &= ~nset->bits;
458				Xbits &= ~nset->bits;
459			} else if (op == '+') {
460				setbits |= nset->bits;
461				clrbits &= ~nset->bits;
462				Xbits &= ~nset->bits;
463			} else if (op == 'X')
464				Xbits |= nset->bits & ~setbits;
465			else
466				break;
467		}
468		if (clrbits) {
469			set->cmd = '-';
470			set->cmd2 = 0;
471			set->bits = clrbits;
472			set++;
473		}
474		if (setbits) {
475			set->cmd = '+';
476			set->cmd2 = 0;
477			set->bits = setbits;
478			set++;
479		}
480		if (Xbits) {
481			set->cmd = 'X';
482			set->cmd2 = 0;
483			set->bits = Xbits;
484			set++;
485		}
486	}
487}
488