[Midnightbsd-cvs] src [9250] trunk: add doas utility from OpenBSD.

laffer1 at midnightbsd.org laffer1 at midnightbsd.org
Sun Jan 29 21:03:38 EST 2017


Revision: 9250
          http://svnweb.midnightbsd.org/src/?rev=9250
Author:   laffer1
Date:     2017-01-29 21:03:38 -0500 (Sun, 29 Jan 2017)
Log Message:
-----------
add doas utility from OpenBSD.  Based on portable version found in mports.

Modified Paths:
--------------
    trunk/etc/Makefile
    trunk/usr.bin/Makefile

Added Paths:
-----------
    trunk/etc/doas.conf
    trunk/usr.bin/doas/
    trunk/usr.bin/doas/LICENSE
    trunk/usr.bin/doas/Makefile
    trunk/usr.bin/doas/doas.1
    trunk/usr.bin/doas/doas.c
    trunk/usr.bin/doas/doas.conf.5
    trunk/usr.bin/doas/doas.h
    trunk/usr.bin/doas/env.c
    trunk/usr.bin/doas/execvpe.c
    trunk/usr.bin/doas/parse.y
    trunk/usr.bin/doas/reallocarray.c
    trunk/usr.bin/doas/tree.h

Modified: trunk/etc/Makefile
===================================================================
--- trunk/etc/Makefile	2017-01-12 23:40:47 UTC (rev 9249)
+++ trunk/etc/Makefile	2017-01-30 02:03:38 UTC (rev 9250)
@@ -14,6 +14,7 @@
 	dhclient.conf \
 	dhcp6c.conf \
 	disktab \
+	doas.conf \
 	fbtab \
 	ftpusers \
 	gettytab \

Added: trunk/etc/doas.conf
===================================================================
--- trunk/etc/doas.conf	                        (rev 0)
+++ trunk/etc/doas.conf	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,3 @@
+# $MidnightBSD$
+permit setenv { -ENV PS1=$DOAS_PS1 SSH_AUTH_SOCK } :wheel 
+permit nopass keepenv root as root


Property changes on: trunk/etc/doas.conf
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Modified: trunk/usr.bin/Makefile
===================================================================
--- trunk/usr.bin/Makefile	2017-01-12 23:40:47 UTC (rev 9249)
+++ trunk/usr.bin/Makefile	2017-01-30 02:03:38 UTC (rev 9250)
@@ -42,6 +42,7 @@
 	ctlstat \
 	cut \
 	dirname \
+	doas \
 	du \
 	ee \
 	elf2aout \

Added: trunk/usr.bin/doas/LICENSE
===================================================================
--- trunk/usr.bin/doas/LICENSE	                        (rev 0)
+++ trunk/usr.bin/doas/LICENSE	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,23 @@
+Copyright (c) 2016, Jesse Smith
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Added: trunk/usr.bin/doas/Makefile
===================================================================
--- trunk/usr.bin/doas/Makefile	                        (rev 0)
+++ trunk/usr.bin/doas/Makefile	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,17 @@
+SRCS=	parse.y doas.c env.c execvpe.c
+
+PROG=	doas
+MAN=	doas.1 doas.conf.5
+
+BINOWN= root
+BINMODE=4555
+
+CFLAGS+= -I${.CURDIR}
+COPTS+=	-Wall
+
+CFLAGS+=-DUSE_PAM -DDOAS_CONF=\"/etc/doas.conf\"
+LDFLAGS+=-lpam
+CFLAGS+=-DHAVE_LOGIN_CAP_H
+LDFLAGS+=-lutil
+
+.include <bsd.prog.mk>


Property changes on: trunk/usr.bin/doas/Makefile
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/doas.1
===================================================================
--- trunk/usr.bin/doas/doas.1	                        (rev 0)
+++ trunk/usr.bin/doas/doas.1	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,109 @@
+.\" $OpenBSD: doas.1,v 1.16 2016/06/11 04:38:21 tedu Exp $
+.\"
+.\"Copyright (c) 2015 Ted Unangst <tedu at openbsd.org>
+.\"
+.\"Permission to use, copy, modify, and distribute this software for any
+.\"purpose with or without fee is hereby granted, provided that the above
+.\"copyright notice and this permission notice appear in all copies.
+.\"
+.\"THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\"WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\"MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\"ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\"OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.Dd $Mdocdate: June 11 2016 $
+.Dt DOAS 1
+.Os
+.Sh NAME
+.Nm doas
+.Nd execute commands as another user
+.Sh SYNOPSIS
+.Nm doas
+.Op Fl ns
+.Op Fl a Ar style
+.Op Fl C Ar config
+.Op Fl u Ar user
+.Ar command
+.Op Ar args
+.Sh DESCRIPTION
+The
+.Nm
+utility executes the given command as another user.
+The
+.Ar command
+argument is mandatory unless
+.Fl C
+or
+.Fl s
+is specified.
+.Pp
+The options are as follows:
+.Bl -tag -width tenletters
+.It Fl a Ar style
+Use the specified authentication style when validating the user,
+as allowed by
+.Pa /etc/login.conf .
+A list of doas-specific authentication methods may be configured by adding an
+.Sq auth-doas
+entry in
+.Xr login.conf 5 .
+.It Fl C Ar config
+Parse and check the configuration file
+.Ar config ,
+then exit.
+If
+.Ar command
+is supplied,
+.Nm
+will also perform command matching.
+In the latter case
+either
+.Sq permit ,
+.Sq permit nopass
+or
+.Sq deny
+will be printed on standard output, depending on command
+matching results.
+No command is executed.
+.It Fl n
+Non interactive mode, fail if
+.Nm
+would prompt for password.
+.It Fl s
+Execute the shell from
+.Ev SHELL
+or
+.Pa /etc/passwd .
+.It Fl u Ar user
+Execute the command as
+.Ar user .
+The default is root.
+.El
+.Sh EXIT STATUS
+.Ex -std doas
+It may fail for one of the following reasons:
+.Pp
+.Bl -bullet -compact
+.It
+The config file
+.Pa /etc/doas.conf
+could not be parsed.
+.It
+The user attempted to run a command which is not permitted.
+.It
+The password was incorrect.
+.It
+The specified command was not found or is not executable.
+.El
+.Sh SEE ALSO
+.Xr su 1 ,
+.Xr doas.conf 5
+.Sh HISTORY
+The
+.Nm
+command first appeared in
+.Ox 5.8 .
+.Sh AUTHORS
+.An Ted Unangst Aq Mt tedu at openbsd.org
\ No newline at end of file


Property changes on: trunk/usr.bin/doas/doas.1
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/doas.c
===================================================================
--- trunk/usr.bin/doas/doas.c	                        (rev 0)
+++ trunk/usr.bin/doas/doas.c	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,555 @@
+/* $OpenBSD: doas.c,v 1.57 2016/06/19 19:29:43 martijn Exp $ */
+/*
+ * Copyright (c) 2015 Ted Unangst <tedu at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#if defined(HAVE_INTTYPES_H)
+#include <inttypes.h>
+#endif
+
+#include <limits.h>
+/*
+#include <login_cap.h>
+#include <bsd_auth.h>
+*/
+#ifndef linux
+#include <readpassphrase.h>
+#endif
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+#include <unistd.h>
+#include <pwd.h>
+#include <grp.h>
+#include <syslog.h>
+#include <errno.h>
+
+#if defined(HAVE_LOGIN_CAP_H)
+#include <login_cap.h>
+#endif
+
+#if defined(USE_BSD_AUTH)
+#include <bsd_auth.h>
+#endif
+
+#if defined(USE_PAM)
+#include <security/pam_appl.h>
+
+#ifndef linux
+#include <security/openpam.h>
+static struct pam_conv pamc = { openpam_ttyconv, NULL };
+#include <fcntl.h>
+#endif // BSD using PAM
+
+#ifdef linux
+#include <security/pam_misc.h>
+static struct pam_conv pamc = { misc_conv, NULL };
+#endif // Linux using PAM
+
+#endif // PAM
+
+#include "doas.h"
+
+static void 
+usage(void)
+{
+	fprintf(stderr, "usage: doas [-ns] [-a style] [-C config] [-u user]"
+	    " command [args]\n");
+	exit(1);
+}
+
+#ifdef linux
+void
+errc(int eval, int code, const char *format)
+{
+   fprintf(stderr, format);
+   exit(code);
+}
+#endif
+
+size_t
+arraylen(const char **arr)
+{
+	size_t cnt = 0;
+
+	while (*arr) {
+		cnt++;
+		arr++;
+	}
+	return cnt;
+}
+
+static int
+parseuid(const char *s, uid_t *uid)
+{
+	struct passwd *pw;
+	const char *errstr;
+
+	if ((pw = getpwnam(s)) != NULL) {
+		*uid = pw->pw_uid;
+		return 0;
+	}
+        #ifndef linux
+	*uid = strtonum(s, 0, UID_MAX, &errstr);
+        #endif
+        #ifdef linux
+        sscanf(s, "%d", uid);
+        #endif
+	if (errstr)
+		return -1;
+	return 0;
+}
+
+static int
+uidcheck(const char *s, uid_t desired)
+{
+	uid_t uid;
+
+	if (parseuid(s, &uid) != 0)
+		return -1;
+	if (uid != desired)
+		return -1;
+	return 0;
+}
+
+static int
+parsegid(const char *s, gid_t *gid)
+{
+	struct group *gr;
+	const char *errstr;
+
+	if ((gr = getgrnam(s)) != NULL) {
+		*gid = gr->gr_gid;
+		return 0;
+	}
+        #ifndef linux
+	*gid = strtonum(s, 0, GID_MAX, &errstr);
+        #endif
+        #ifdef linux
+        sscanf(s, "%d", gid);
+        #endif
+	if (errstr)
+		return -1;
+	return 0;
+}
+
+static int
+match(uid_t uid, gid_t *groups, int ngroups, uid_t target, const char *cmd,
+    const char **cmdargs, struct rule *r)
+{
+	int i;
+
+	if (r->ident[0] == ':') {
+		gid_t rgid;
+		if (parsegid(r->ident + 1, &rgid) == -1)
+			return 0;
+		for (i = 0; i < ngroups; i++) {
+			if (rgid == groups[i])
+				break;
+		}
+		if (i == ngroups)
+			return 0;
+	} else {
+		if (uidcheck(r->ident, uid) != 0)
+			return 0;
+	}
+	if (r->target && uidcheck(r->target, target) != 0)
+		return 0;
+	if (r->cmd) {
+		if (strcmp(r->cmd, cmd))
+			return 0;
+		if (r->cmdargs) {
+			/* if arguments were given, they should match explicitly */
+			for (i = 0; r->cmdargs[i]; i++) {
+				if (!cmdargs[i])
+					return 0;
+				if (strcmp(r->cmdargs[i], cmdargs[i]))
+					return 0;
+			}
+			if (cmdargs[i])
+				return 0;
+		}
+	}
+	return 1;
+}
+
+static int
+permit(uid_t uid, gid_t *groups, int ngroups, struct rule **lastr,
+    uid_t target, const char *cmd, const char **cmdargs)
+{
+	int i;
+
+	*lastr = NULL;
+	for (i = 0; i < nrules; i++) {
+		if (match(uid, groups, ngroups, target, cmd,
+		    cmdargs, rules[i]))
+			*lastr = rules[i];
+	}
+	if (!*lastr)
+		return 0;
+	return (*lastr)->action == PERMIT;
+}
+
+static void
+parseconfig(const char *filename, int checkperms)
+{
+	extern FILE *yyfp;
+	extern int yyparse(void);
+	struct stat sb;
+
+	yyfp = fopen(filename, "r");
+	if (!yyfp)
+		err(1, checkperms ? "doas is not enabled, %s" :
+		    "could not open config file %s", filename);
+
+	if (checkperms) {
+		if (fstat(fileno(yyfp), &sb) != 0)
+			err(1, "fstat(\"%s\")", filename);
+		if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)
+			errx(1, "%s is writable by group or other", filename);
+		if (sb.st_uid != 0)
+			errx(1, "%s is not owned by root", filename);
+	}
+
+	yyparse();
+	fclose(yyfp);
+	if (parse_errors)
+		exit(1);
+}
+
+static void 
+checkconfig(const char *confpath, int argc, char **argv,
+    uid_t uid, gid_t *groups, int ngroups, uid_t target)
+{
+	struct rule *rule;
+
+	setresuid(uid, uid, uid);
+	parseconfig(confpath, 0);
+	if (!argc)
+		exit(0);
+
+	if (permit(uid, groups, ngroups, &rule, target, argv[0],
+	    (const char **)argv + 1)) {
+		printf("permit%s\n", (rule->options & NOPASS) ? " nopass" : "");
+		exit(0);
+	} else {
+		printf("deny\n");
+		exit(1);
+	}
+}
+
+int
+main(int argc, char **argv)
+{
+	const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
+	    "/usr/local/bin:/usr/local/sbin";
+	const char *confpath = NULL;
+	char *shargv[] = { NULL, NULL };
+	char *sh;
+	const char *cmd;
+	char cmdline[LINE_MAX];
+	char myname[_PW_NAME_LEN + 1];
+	struct passwd *pw;
+	struct rule *rule;
+	uid_t uid;
+	uid_t target = 0;
+	gid_t groups[NGROUPS_MAX + 1];
+	int ngroups;
+	int i, ch;
+	int sflag = 0;
+	int nflag = 0;
+	char cwdpath[PATH_MAX];
+	const char *cwd;
+	char *login_style = NULL;
+	char **envp;
+        #ifdef USE_PAM
+        int temp_stdout;
+        #endif
+
+        #ifndef linux
+	setprogname("doas");
+        #endif
+
+        /*
+	if (pledge("stdio rpath getpw tty proc exec id", NULL) == -1)
+		err(1, "pledge");
+        */
+
+        #ifndef linux
+	closefrom(STDERR_FILENO + 1);
+        #endif
+
+	uid = getuid();
+
+	while ((ch = getopt(argc, argv, "a:C:nsu:")) != -1) {
+		switch (ch) {
+		case 'a':
+			login_style = optarg;
+			break;
+		case 'C':
+			confpath = optarg;
+			break;
+		case 'u':
+			if (parseuid(optarg, &target) != 0)
+				errx(1, "unknown user");
+			break;
+		case 'n':
+			nflag = 1;
+			break;
+		case 's':
+			sflag = 1;
+			break;
+		default:
+			usage();
+			break;
+		}
+	}
+	argv += optind;
+	argc -= optind;
+
+	if (confpath) {
+		if (sflag)
+			usage();
+	} else if ((!sflag && !argc) || (sflag && argc))
+		usage();
+
+	pw = getpwuid(uid);
+	if (!pw)
+		err(1, "getpwuid failed");
+        #ifndef linux
+	if (strlcpy(myname, pw->pw_name, sizeof(myname)) >= sizeof(myname))
+		errx(1, "pw_name too long");
+        #endif
+        #ifdef linux
+        strncpy(myname, pw->pw_name, sizeof(myname));
+        #endif
+	ngroups = getgroups(NGROUPS_MAX, groups);
+	if (ngroups == -1)
+		err(1, "can't get groups");
+	groups[ngroups++] = getgid();
+
+	if (sflag) {
+		sh = getenv("SHELL");
+		if (sh == NULL || *sh == '\0')
+			shargv[0] = pw->pw_shell;
+		else
+			shargv[0] = sh;
+		argv = shargv;
+		argc = 1;
+	}
+
+	if (confpath) {
+		checkconfig(confpath, argc, argv, uid, groups, ngroups,
+		    target);
+		exit(1);	/* fail safe */
+	}
+
+#if defined(USE_PAM)
+	pam_handle_t *pamh = NULL;
+	int pam_err;
+	int pam_silent = PAM_SILENT;
+#endif
+
+	parseconfig(DOAS_CONF, 1);
+
+	/* cmdline is used only for logging, no need to abort on truncate */
+        #ifndef linux
+	(void) strlcpy(cmdline, argv[0], sizeof(cmdline));
+	for (i = 1; i < argc; i++) {
+		if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
+			break;
+		if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
+			break;
+	}
+        #endif
+        #ifdef linux
+        strncpy(cmdline, argv[0], sizeof(cmdline));
+        for (i = 1; i < argc; i++) {
+                strncat(cmdline, " ", sizeof(cmdline));
+                strncat(cmdline, argv[i], sizeof(cmdline));
+        }
+        #endif
+
+	cmd = argv[0];
+	if (!permit(uid, groups, ngroups, &rule, target, cmd,
+	    (const char**)argv + 1)) {
+		syslog(LOG_AUTHPRIV | LOG_NOTICE,
+		    "failed command for %s: %s", myname, cmdline);
+		errc(1, EPERM, NULL);
+	}
+
+	if (!(rule->options & NOPASS)) {
+#if defined(USE_BSD_AUTH)      
+		char *challenge = NULL, *response, rbuf[1024], cbuf[128];
+		auth_session_t *as;
+
+		if (nflag)
+			errx(1, "Authorization required");
+
+		if (!(as = auth_userchallenge(myname, login_style, "auth-doas",
+		    &challenge)))
+			errx(1, "Authorization failed");
+		if (!challenge) {
+			char host[MAXHOSTNAME + 1];
+			if (gethostname(host, sizeof(host)))
+				snprintf(host, sizeof(host), "?");
+			snprintf(cbuf, sizeof(cbuf),
+			    "\rdoas (%.32s@%.32s) password: ", myname, host);
+			challenge = cbuf;
+		}
+		response = readpassphrase(challenge, rbuf, sizeof(rbuf),
+		    RPP_REQUIRE_TTY);
+		if (response == NULL && errno == ENOTTY) {
+			syslog(LOG_AUTHPRIV | LOG_NOTICE,
+			    "tty required for %s", myname);
+			errx(1, "a tty is required");
+		}
+		if (!auth_userresponse(as, response, 0)) {
+			syslog(LOG_AUTHPRIV | LOG_NOTICE,
+			    "failed auth for %s", myname);
+			errc(1, EPERM, NULL);
+		}
+		explicit_bzero(rbuf, sizeof(rbuf));
+#elif defined(USE_PAM)
+#define PAM_END(msg) do { 						\
+	syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); 	\
+	warnx("%s: %s", msg, pam_strerror(pamh, pam_err));		\
+	pam_end(pamh, pam_err);						\
+	exit(EXIT_FAILURE);						\
+} while (/*CONSTCOND*/0)
+
+                /* force password prompt to display on stderr, not stdout */
+                temp_stdout = dup(1);
+                close(1);
+                dup2(2, 1);
+		pam_err = pam_start("doas", myname, &pamc, &pamh);
+		if (pam_err != PAM_SUCCESS) {
+			if (pamh != NULL)
+				PAM_END("pam_start");
+			syslog(LOG_ERR, "pam_start failed: %s",
+			    pam_strerror(pamh, pam_err));
+			errx(EXIT_FAILURE, "pam_start failed");
+		}
+
+		switch (pam_err = pam_authenticate(pamh, pam_silent)) {
+		case PAM_SUCCESS:
+			switch (pam_err = pam_acct_mgmt(pamh, pam_silent)) {
+			case PAM_SUCCESS:
+				break;
+
+			case PAM_NEW_AUTHTOK_REQD:
+				pam_err = pam_chauthtok(pamh,
+				    pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
+				if (pam_err != PAM_SUCCESS)
+					PAM_END("pam_chauthtok");
+				break;
+
+			case PAM_AUTH_ERR:
+			case PAM_USER_UNKNOWN:
+			case PAM_MAXTRIES:
+				syslog(LOG_AUTHPRIV | LOG_NOTICE,
+				    "failed auth for %s", myname);
+                                errx(EXIT_FAILURE, "second authentication failed");
+				break;
+
+			default:
+				PAM_END("pam_acct_mgmt");
+				break;
+			}
+			break;
+
+		case PAM_AUTH_ERR:
+		case PAM_USER_UNKNOWN:
+		case PAM_MAXTRIES:
+			syslog(LOG_AUTHPRIV | LOG_NOTICE,
+			    "failed auth for %s", myname);
+                        errx(EXIT_FAILURE, "authentication failed");
+			break;
+
+		default:
+			PAM_END("pam_authenticate");
+			break;
+		}
+		pam_end(pamh, pam_err);
+#else
+#error	No auth module!
+#endif
+
+	}
+
+        /*
+	if (pledge("stdio rpath getpw exec id", NULL) == -1)
+		err(1, "pledge");
+        */
+	pw = getpwuid(target);
+	if (!pw)
+		errx(1, "no passwd entry for target");
+
+#if defined(HAVE_LOGIN_CAP_H)
+	if (setusercontext(NULL, pw, target, LOGIN_SETGROUP |
+	    LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
+	    LOGIN_SETUSER) != 0)
+		errx(1, "failed to set user context for target");
+#endif
+        /*
+	if (pledge("stdio rpath exec", NULL) == -1)
+		err(1, "pledge");
+        */
+
+	if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
+		cwd = "(failed)";
+	else
+		cwd = cwdpath;
+
+	/*
+        if (pledge("stdio exec", NULL) == -1)
+		err(1, "pledge");
+        */
+        /* Re-establish stdout */
+        #ifdef USE_PAM
+        if (!(rule->options & NOPASS))
+        {
+          close(1);
+          dup2(temp_stdout, 1);
+        }
+        #endif
+
+#ifndef HAVE_LOGIN_CAP_H
+        /* If we effectively are root, set the UID to actually be root to avoid
+           permission errors. */
+        if (target != 0)
+           setuid(target);
+        if ( geteuid() == ROOT_UID )
+           setuid(ROOT_UID);
+#endif
+
+	syslog(LOG_AUTHPRIV | LOG_INFO, "%s ran command %s as %s from %s",
+	    myname, cmdline, pw->pw_name, cwd);
+
+	envp = prepenv(rule);
+
+	if (rule->cmd) {
+		if (setenv("PATH", safepath, 1) == -1)
+			err(1, "failed to set PATH '%s'", safepath);
+	}
+	execvpe(cmd, argv, envp);
+	if (errno == ENOENT)
+		errx(1, "%s: command not found", cmd);
+	err(1, "%s", cmd);
+}


Property changes on: trunk/usr.bin/doas/doas.c
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/doas.conf.5
===================================================================
--- trunk/usr.bin/doas/doas.conf.5	                        (rev 0)
+++ trunk/usr.bin/doas/doas.conf.5	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,142 @@
+.\" $OpenBSD: doas.conf.5,v 1.26 2016/06/11 17:17:10 tedu Exp $
+.\"
+.\"Copyright (c) 2015 Ted Unangst <tedu at openbsd.org>
+.\"
+.\"Permission to use, copy, modify, and distribute this software for any
+.\"purpose with or without fee is hereby granted, provided that the above
+.\"copyright notice and this permission notice appear in all copies.
+.\"
+.\"THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\"WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\"MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\"ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\"WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\"OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.Dd $Mdocdate: June 11 2016 $
+.Dt DOAS.CONF 5
+.Os
+.Sh NAME
+.Nm doas.conf
+.Nd doas configuration file
+.Sh SYNOPSIS
+.Nm /usr/local/etc/doas.conf
+.Sh DESCRIPTION
+The
+.Xr doas 1
+utility executes commands as other users according to the rules
+in the
+.Nm
+configuration file.
+.Pp
+The rules have the following format:
+.Bd -ragged -offset indent
+.Ic permit Ns | Ns Ic deny
+.Op Ar options
+.Ar identity
+.Op Ic as Ar target
+.Op Ic cmd Ar command Op Ic args ...
+.Ed
+.Pp
+Rules consist of the following parts:
+.Bl -tag -width 11n
+.It Ic permit Ns | Ns Ic deny
+The action to be taken if this rule matches.
+.It Ar options
+Options are:
+.Bl -tag -width keepenv
+.It Ic nopass
+The user is not required to enter a password.
+.It Ic keepenv
+The user's environment is maintained.
+The default is to reset the environment, except for the variables
+.Ev DISPLAY ,
+.Ev HOME ,
+.Ev LOGNAME ,
+.Ev MAIL ,
+.Ev PATH ,
+.Ev TERM ,
+.Ev USER
+and
+.Ev USERNAME .
+.It Ic keepenv { Oo Ar variable ... Oc Ic }
+In addition to the variables mentioned above, keep the space-separated
+specified variables.
+.El
+.It Ar identity
+The username to match.
+Groups may be specified by prepending a colon
+.Pq Sq \&: .
+Numeric IDs are also accepted.
+.It Ic as Ar target
+The target user the running user is allowed to run the command as.
+The default is all users.
+.It Ic cmd Ar command
+The command the user is allowed or denied to run.
+The default is all commands.
+Be advised that it is best to specify absolute paths.
+If a relative path is specified, only a restricted
+.Ev PATH
+will be searched.
+.It Ic args ...
+Arguments to command.
+The command arguments provided by the user need to match those specified.
+The keyword
+.Ic args
+alone means that command must be run without any arguments.
+.El
+.Pp
+The last matching rule determines the action taken.
+If no rule matches, the action is denied.
+.Pp
+Comments can be put anywhere in the file using a hash mark
+.Pq Sq # ,
+and extend to the end of the current line.
+.Pp
+The following quoting rules apply:
+.Bl -dash
+.It
+The text between a pair of double quotes
+.Pq Sq \&"
+is taken as is.
+.It
+The backslash character
+.Pq Sq \e
+escapes the next character, including new line characters, outside comments;
+as a result, comments may not be extended over multiple lines.
+.It
+If quotes or backslashes are used in a word,
+it is not considered a keyword.
+.El
+.Sh EXAMPLES
+The following example permits users in group wsrc to build ports,
+wheel to execute commands as any user while keeping the environment
+variables
+.Ev ENV ,
+.Ev PS1 ,
+and
+.Ev SSH_AUTH_SOCK ,
+permits tedu to run procmap as root without a password,
+and additionally permits root to run unrestricted commands as itself.
+.Bd -literal -offset indent
+# Non-exhaustive list of variables needed to
+# build release(8) and ports(7)
+permit nopass keepenv { \e
+        FTPMODE PKG_CACHE PKG_PATH SM_PATH SSH_AUTH_SOCK \e
+        DESTDIR DISTDIR FETCH_CMD FLAVOR GROUP MAKE MAKECONF \e
+        MULTI_PACKAGES NOMAN OKAY_FILES OWNER PKG_DBDIR \e
+        PKG_DESTDIR PKG_TMPDIR PORTSDIR RELEASEDIR SHARED_ONLY \e
+        SUBPACKAGE WRKOBJDIR SUDO_PORT_V1 } :wsrc
+permit nopass keepenv { ENV PS1 SSH_AUTH_SOCK } :wheel
+permit nopass tedu as root cmd /usr/sbin/procmap
+permit nopass keepenv root as root
+.Ed
+.Sh SEE ALSO
+.Xr doas 1
+.Sh HISTORY
+The
+.Nm
+configuration file first appeared in
+.Ox 5.8 .
+.Sh AUTHORS
+.An Ted Unangst Aq Mt tedu at openbsd.org


Property changes on: trunk/usr.bin/doas/doas.conf.5
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/doas.h
===================================================================
--- trunk/usr.bin/doas/doas.h	                        (rev 0)
+++ trunk/usr.bin/doas/doas.h	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,50 @@
+/* $OpenBSD: doas.h,v 1.8 2016/06/19 19:29:43 martijn Exp $ */
+struct rule {
+	int action;
+	int options;
+	const char *ident;
+	const char *target;
+	const char *cmd;
+	const char **cmdargs;
+	const char **envlist;
+};
+
+extern struct rule **rules;
+extern int nrules, maxrules;
+extern int parse_errors;
+
+size_t arraylen(const char **);
+
+char **prepenv(struct rule *);
+
+#define PERMIT	1
+#define DENY	2
+
+#define NOPASS		0x1
+#define KEEPENV		0x2
+
+#ifndef UID_MAX
+#define UID_MAX 65535
+#endif
+
+#ifndef GID_MAX
+#define GID_MAX 65535
+#endif
+
+#ifndef ROOT_UID
+#define ROOT_UID 0
+#endif
+
+#ifndef _PW_NAME_LEN
+#define _PW_NAME_LEN 32
+#endif
+
+void *reallocarray(void *ptr, size_t nmemb, size_t size);
+
+#if !defined(HAVE_EXECVPE)
+int execvpe(const char *file, char * const *argv, char * const *envp);
+#endif	/* !HAVE_EXECVPE */
+
+#ifdef linux
+void errc(int eval, int code, const char *format);
+#endif


Property changes on: trunk/usr.bin/doas/doas.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/env.c
===================================================================
--- trunk/usr.bin/doas/env.c	                        (rev 0)
+++ trunk/usr.bin/doas/env.c	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,182 @@
+/* $OpenBSD: env.c,v 1.2 2016/06/19 19:29:43 martijn Exp $ */
+/*
+ * Copyright (c) 2016 Ted Unangst <tedu at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/tree.h>
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "doas.h"
+
+struct envnode {
+	RB_ENTRY(envnode) node;
+	const char *key;
+	const char *value;
+};
+
+struct env {
+	RB_HEAD(envtree, envnode) root;
+	u_int count;
+};
+
+int envcmp(struct envnode *a, struct envnode *b);
+
+int
+envcmp(struct envnode *a, struct envnode *b)
+{
+	return strcmp(a->key, b->key);
+}
+RB_GENERATE_STATIC(envtree, envnode, node, envcmp)
+
+struct env *createenv(char **);
+struct env *filterenv(struct env *, struct rule *);
+char **flattenenv(struct env *);
+
+struct env *
+createenv(char **envp)
+{
+	struct env *env;
+	u_int i;
+
+	env = malloc(sizeof(*env));
+	if (!env)
+		err(1, NULL);
+	RB_INIT(&env->root);
+	env->count = 0;
+
+	for (i = 0; envp[i] != NULL; i++) {
+		struct envnode *node;
+		const char *e, *eq;
+
+		e = envp[i];
+
+		if ((eq = strchr(e, '=')) == NULL || eq == e)
+			continue;
+		node = malloc(sizeof(*node));
+		if (!node)
+			err(1, NULL);
+		node->key = strndup(envp[i], eq - e);
+		node->value = strdup(eq + 1);
+		if (!node->key || !node->value)
+			err(1, NULL);
+		if (RB_FIND(envtree, &env->root, node)) {
+			free((char *)node->key);
+			free((char *)node->value);
+			free(node);
+		} else {
+			RB_INSERT(envtree, &env->root, node);
+			env->count++;
+		}
+	}
+	return env;
+}
+
+char **
+flattenenv(struct env *env)
+{
+	char **envp;
+	struct envnode *node;
+	u_int i;
+
+        envp = reallocarray(NULL, (env->count + 1), sizeof(char *));
+	if (!envp)
+		err(1, NULL);
+	i = 0;
+	RB_FOREACH(node, envtree, &env->root) {
+		if (asprintf(&envp[i], "%s=%s", node->key, node->value) == -1)
+			err(1, NULL);
+		i++;
+	}
+	envp[i] = NULL;
+	return envp;
+}
+
+static void
+copyenv(struct env *orig, struct env *copy, const char **envlist)
+{
+	struct envnode *node, key;
+	u_int i;
+
+	for (i = 0; envlist[i]; i++) {
+		key.key = envlist[i];
+		if ((node = RB_FIND(envtree, &orig->root, &key))) {
+			RB_REMOVE(envtree, &orig->root, node);
+			orig->count--;
+			RB_INSERT(envtree, &copy->root, node);
+			copy->count++;
+		}
+	}
+}
+
+struct env *
+filterenv(struct env *orig, struct rule *rule)
+{
+	const char *safeset[] = {
+		"DISPLAY", "HOME", "LOGNAME", "MAIL",
+		"PATH", "TERM", "USER", "USERNAME",
+		NULL
+	};
+	const char *badset[] = {
+		"ENV",
+		NULL
+	};
+	struct env *copy;
+	struct envnode *node, key;
+	u_int i;
+
+	if ((rule->options & KEEPENV) && !rule->envlist) {
+		for (i = 0; badset[i]; i++) {
+			key.key = badset[i];
+			if ((node = RB_FIND(envtree, &orig->root, &key))) {
+				RB_REMOVE(envtree, &orig->root, node);
+				free((char *)node->key);
+				free((char *)node->value);
+				free(node);
+				orig->count--;
+			}
+		}
+		return orig;
+	}
+
+	copy = malloc(sizeof(*copy));
+	if (!copy)
+		err(1, NULL);
+	RB_INIT(&copy->root);
+	copy->count = 0;
+
+	if (rule->envlist)
+		copyenv(orig, copy, rule->envlist);
+	copyenv(orig, copy, safeset);
+
+	return copy;
+}
+
+char **
+prepenv(struct rule *rule)
+{
+	extern char **environ;
+	struct env *env;
+	
+	env = createenv(environ);
+	env = filterenv(env, rule);
+	return flattenenv(env);
+}


Property changes on: trunk/usr.bin/doas/env.c
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/execvpe.c
===================================================================
--- trunk/usr.bin/doas/execvpe.c	                        (rev 0)
+++ trunk/usr.bin/doas/execvpe.c	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,46 @@
+/*-
+ * Copyright (C) 2015 NONAKA Kimihiro <nonakap at gmail.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <unistd.h>
+
+#include "doas.h"
+
+#if !defined(HAVE_EXECVPE)
+
+extern char **environ;
+
+int
+execvpe(const char *file, char * const *argv, char * const *envp)
+{
+	char **oldenvp = environ;
+	int error;
+
+	environ = (char **)(long)envp;	/* XXX */
+	error = execvp(file, argv);
+	environ = oldenvp;
+	return error;
+}
+
+#endif	/* !HAVE_EXECVPE */


Property changes on: trunk/usr.bin/doas/execvpe.c
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/parse.y
===================================================================
--- trunk/usr.bin/doas/parse.y	                        (rev 0)
+++ trunk/usr.bin/doas/parse.y	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,326 @@
+/* $OpenBSD: parse.y,v 1.18 2016/06/07 16:49:23 tedu Exp $ */
+/*
+ * Copyright (c) 2015 Ted Unangst <tedu at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+%{
+#include <sys/types.h>
+#include <ctype.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <err.h>
+
+#include "doas.h"
+
+typedef struct {
+	union {
+		struct {
+			int action;
+			int options;
+			const char *cmd;
+			const char **cmdargs;
+			const char **envlist;
+		};
+		const char *str;
+	};
+	int lineno;
+	int colno;
+} yystype;
+#define YYSTYPE yystype
+
+FILE *yyfp;
+
+struct rule **rules;
+int nrules, maxrules;
+int parse_errors = 0;
+
+void yyerror(const char *, ...);
+int yylex(void);
+int yyparse(void);
+
+%}
+
+%token TPERMIT TDENY TAS TCMD TARGS
+%token TNOPASS TKEEPENV
+%token TSTRING
+
+%%
+
+grammar:	/* empty */
+		| grammar '\n'
+		| grammar rule '\n'
+		| error '\n'
+		;
+
+rule:		action ident target cmd {
+			struct rule *r;
+			r = calloc(1, sizeof(*r));
+			if (!r)
+				errx(1, "can't allocate rule");
+			r->action = $1.action;
+			r->options = $1.options;
+			r->envlist = $1.envlist;
+			r->ident = $2.str;
+			r->target = $3.str;
+			r->cmd = $4.cmd;
+			r->cmdargs = $4.cmdargs;
+			if (nrules == maxrules) {
+				if (maxrules == 0)
+					maxrules = 63;
+				else
+					maxrules *= 2;
+				if (!(rules = reallocarray(rules, maxrules,
+				    sizeof(*rules))))
+					errx(1, "can't allocate rules");
+			}
+			rules[nrules++] = r;
+		} ;
+
+action:		TPERMIT options {
+			$$.action = PERMIT;
+			$$.options = $2.options;
+			$$.envlist = $2.envlist;
+		} | TDENY {
+			$$.action = DENY;
+		} ;
+
+options:	/* none */
+		| options option {
+			$$.options = $1.options | $2.options;
+			$$.envlist = $1.envlist;
+			if ($2.envlist) {
+				if ($$.envlist) {
+					yyerror("can't have two keepenv sections");
+					YYERROR;
+				} else
+					$$.envlist = $2.envlist;
+			}
+		} ;
+option:		TNOPASS {
+			$$.options = NOPASS;
+		} | TKEEPENV {
+			$$.options = KEEPENV;
+		} | TKEEPENV '{' envlist '}' {
+			$$.options = KEEPENV;
+			$$.envlist = $3.envlist;
+		} ;
+
+envlist:	/* empty */ {
+			if (!($$.envlist = calloc(1, sizeof(char *))))
+				errx(1, "can't allocate envlist");
+		} | envlist TSTRING {
+			int nenv = arraylen($1.envlist);
+			if (!($$.envlist = reallocarray($1.envlist, nenv + 2,
+			    sizeof(char *))))
+				errx(1, "can't allocate envlist");
+			$$.envlist[nenv] = $2.str;
+			$$.envlist[nenv + 1] = NULL;
+		}
+
+
+ident:		TSTRING {
+			$$.str = $1.str;
+		} ;
+
+target:		/* optional */ {
+			$$.str = NULL;
+		} | TAS TSTRING {
+			$$.str = $2.str;
+		} ;
+
+cmd:		/* optional */ {
+			$$.cmd = NULL;
+			$$.cmdargs = NULL;
+		} | TCMD TSTRING args {
+			$$.cmd = $2.str;
+			$$.cmdargs = $3.cmdargs;
+		} ;
+
+args:		/* empty */ {
+			$$.cmdargs = NULL;
+		} | TARGS argslist {
+			$$.cmdargs = $2.cmdargs;
+		} ;
+
+argslist:	/* empty */ {
+			if (!($$.cmdargs = calloc(1, sizeof(char *))))
+				errx(1, "can't allocate args");
+		} | argslist TSTRING {
+			int nargs = arraylen($1.cmdargs);
+			if (!($$.cmdargs = reallocarray($1.cmdargs, nargs + 2,
+			    sizeof(char *))))
+				errx(1, "can't allocate args");
+			$$.cmdargs[nargs] = $2.str;
+			$$.cmdargs[nargs + 1] = NULL;
+		} ;
+
+%%
+
+void
+yyerror(const char *fmt, ...)
+{
+	va_list va;
+
+	fprintf(stderr, "doas: ");
+	va_start(va, fmt);
+	vfprintf(stderr, fmt, va);
+	va_end(va);
+	fprintf(stderr, " at line %d\n", yylval.lineno + 1);
+	parse_errors++;
+}
+
+struct keyword {
+	const char *word;
+	int token;
+} keywords[] = {
+	{ "deny", TDENY },
+	{ "permit", TPERMIT },
+	{ "as", TAS },
+	{ "cmd", TCMD },
+	{ "args", TARGS },
+	{ "nopass", TNOPASS },
+	{ "keepenv", TKEEPENV },
+};
+
+int
+yylex(void)
+{
+	char buf[1024], *ebuf, *p, *str;
+	int i, c, quotes = 0, escape = 0, qpos = -1, nonkw = 0;
+
+	p = buf;
+	ebuf = buf + sizeof(buf);
+
+repeat:
+	/* skip whitespace first */
+	for (c = getc(yyfp); c == ' ' || c == '\t'; c = getc(yyfp))
+		yylval.colno++;
+
+	/* check for special one-character constructions */
+	switch (c) {
+		case '\n':
+			yylval.colno = 0;
+			yylval.lineno++;
+			/* FALLTHROUGH */
+		case '{':
+		case '}':
+			return c;
+		case '#':
+			/* skip comments; NUL is allowed; no continuation */
+			while ((c = getc(yyfp)) != '\n')
+				if (c == EOF)
+					goto eof;
+			yylval.colno = 0;
+			yylval.lineno++;
+			return c;
+		case EOF:
+			goto eof;
+	}
+
+	/* parsing next word */
+	for (;; c = getc(yyfp), yylval.colno++) {
+		switch (c) {
+		case '\0':
+			yyerror("unallowed character NUL in column %d",
+			    yylval.colno + 1);
+			escape = 0;
+			continue;
+		case '\\':
+			escape = !escape;
+			if (escape)
+				continue;
+			break;
+		case '\n':
+			if (quotes)
+				yyerror("unterminated quotes in column %d",
+				    qpos + 1);
+			if (escape) {
+				nonkw = 1;
+				escape = 0;
+				yylval.colno = 0;
+				yylval.lineno++;
+				continue;
+			}
+			goto eow;
+		case EOF:
+			if (escape)
+				yyerror("unterminated escape in column %d",
+				    yylval.colno);
+			if (quotes)
+				yyerror("unterminated quotes in column %d",
+				    qpos + 1);
+			goto eow;
+			/* FALLTHROUGH */
+		case '{':
+		case '}':
+		case '#':
+		case ' ':
+		case '\t':
+			if (!escape && !quotes)
+				goto eow;
+			break;
+		case '"':
+			if (!escape) {
+				quotes = !quotes;
+				if (quotes) {
+					nonkw = 1;
+					qpos = yylval.colno;
+				}
+				continue;
+			}
+		}
+		*p++ = c;
+		if (p == ebuf) {
+			yyerror("too long line");
+			p = buf;
+		}
+		escape = 0;
+	}
+
+eow:
+	*p = 0;
+	if (c != EOF)
+		ungetc(c, yyfp);
+	if (p == buf) {
+		/*
+		 * There could be a number of reasons for empty buffer,
+		 * and we handle all of them here, to avoid cluttering
+		 * the main loop.
+		 */
+		if (c == EOF)
+			goto eof;
+		else if (qpos == -1)    /* accept, e.g., empty args: cmd foo args "" */
+			goto repeat;
+	}
+	if (!nonkw) {
+		for (i = 0; (size_t)i < sizeof(keywords) / sizeof(keywords[0]); i++) {
+			if (strcmp(buf, keywords[i].word) == 0)
+				return keywords[i].token;
+		}
+	}
+	if ((str = strdup(buf)) == NULL)
+		err(1, "strdup");
+	yylval.str = str;
+	return TSTRING;
+
+eof:
+	if (ferror(yyfp))
+		yyerror("input error reading config");
+	return 0;
+}

Added: trunk/usr.bin/doas/reallocarray.c
===================================================================
--- trunk/usr.bin/doas/reallocarray.c	                        (rev 0)
+++ trunk/usr.bin/doas/reallocarray.c	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,39 @@
+/*	$OpenBSD: reallocarray.c,v 1.3 2015/09/13 08:31:47 guenther Exp $	*/
+/*
+ * Copyright (c) 2008 Otto Moerbeek <otto at drijf.net>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/*
+ * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
+ * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
+ */
+#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
+
+void *
+reallocarray(void *optr, size_t nmemb, size_t size)
+{
+	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
+	    nmemb > 0 && SIZE_MAX / nmemb < size) {
+		errno = ENOMEM;
+		return NULL;
+	}
+	return realloc(optr, size * nmemb);
+}
+//DEF_WEAK(reallocarray);


Property changes on: trunk/usr.bin/doas/reallocarray.c
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property
Added: trunk/usr.bin/doas/tree.h
===================================================================
--- trunk/usr.bin/doas/tree.h	                        (rev 0)
+++ trunk/usr.bin/doas/tree.h	2017-01-30 02:03:38 UTC (rev 9250)
@@ -0,0 +1,748 @@
+/*	$OpenBSD: tree.h,v 1.14 2015/05/25 03:07:49 deraadt Exp $	*/
+/*
+ * Copyright 2002 Niels Provos <provos at citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef	_SYS_TREE_H_
+#define	_SYS_TREE_H_
+
+/*
+ * This file defines data structures for different types of trees:
+ * splay trees and red-black trees.
+ *
+ * A splay tree is a self-organizing data structure.  Every operation
+ * on the tree causes a splay to happen.  The splay moves the requested
+ * node to the root of the tree and partly rebalances it.
+ *
+ * This has the benefit that request locality causes faster lookups as
+ * the requested nodes move to the top of the tree.  On the other hand,
+ * every lookup causes memory writes.
+ *
+ * The Balance Theorem bounds the total access time for m operations
+ * and n inserts on an initially empty tree as O((m + n)lg n).  The
+ * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
+ *
+ * A red-black tree is a binary search tree with the node color as an
+ * extra attribute.  It fulfills a set of conditions:
+ *	- every search path from the root to a leaf consists of the
+ *	  same number of black nodes,
+ *	- each red node (except for the root) has a black parent,
+ *	- each leaf node is black.
+ *
+ * Every operation on a red-black tree is bounded as O(lg n).
+ * The maximum height of a red-black tree is 2lg (n+1).
+ */
+
+#define SPLAY_HEAD(name, type)						\
+struct name {								\
+	struct type *sph_root; /* root of the tree */			\
+}
+
+#define SPLAY_INITIALIZER(root)						\
+	{ NULL }
+
+#define SPLAY_INIT(root) do {						\
+	(root)->sph_root = NULL;					\
+} while (0)
+
+#define SPLAY_ENTRY(type)						\
+struct {								\
+	struct type *spe_left; /* left element */			\
+	struct type *spe_right; /* right element */			\
+}
+
+#define SPLAY_LEFT(elm, field)		(elm)->field.spe_left
+#define SPLAY_RIGHT(elm, field)		(elm)->field.spe_right
+#define SPLAY_ROOT(head)		(head)->sph_root
+#define SPLAY_EMPTY(head)		(SPLAY_ROOT(head) == NULL)
+
+/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
+#define SPLAY_ROTATE_RIGHT(head, tmp, field) do {			\
+	SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field);	\
+	SPLAY_RIGHT(tmp, field) = (head)->sph_root;			\
+	(head)->sph_root = tmp;						\
+} while (0)
+
+#define SPLAY_ROTATE_LEFT(head, tmp, field) do {			\
+	SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field);	\
+	SPLAY_LEFT(tmp, field) = (head)->sph_root;			\
+	(head)->sph_root = tmp;						\
+} while (0)
+
+#define SPLAY_LINKLEFT(head, tmp, field) do {				\
+	SPLAY_LEFT(tmp, field) = (head)->sph_root;			\
+	tmp = (head)->sph_root;						\
+	(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);		\
+} while (0)
+
+#define SPLAY_LINKRIGHT(head, tmp, field) do {				\
+	SPLAY_RIGHT(tmp, field) = (head)->sph_root;			\
+	tmp = (head)->sph_root;						\
+	(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);	\
+} while (0)
+
+#define SPLAY_ASSEMBLE(head, node, left, right, field) do {		\
+	SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field);	\
+	SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
+	SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field);	\
+	SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field);	\
+} while (0)
+
+/* Generates prototypes and inline functions */
+
+#define SPLAY_PROTOTYPE(name, type, field, cmp)				\
+void name##_SPLAY(struct name *, struct type *);			\
+void name##_SPLAY_MINMAX(struct name *, int);				\
+struct type *name##_SPLAY_INSERT(struct name *, struct type *);		\
+struct type *name##_SPLAY_REMOVE(struct name *, struct type *);		\
+									\
+/* Finds the node with the same key as elm */				\
+static __inline struct type *						\
+name##_SPLAY_FIND(struct name *head, struct type *elm)			\
+{									\
+	if (SPLAY_EMPTY(head))						\
+		return(NULL);						\
+	name##_SPLAY(head, elm);					\
+	if ((cmp)(elm, (head)->sph_root) == 0)				\
+		return (head->sph_root);				\
+	return (NULL);							\
+}									\
+									\
+static __inline struct type *						\
+name##_SPLAY_NEXT(struct name *head, struct type *elm)			\
+{									\
+	name##_SPLAY(head, elm);					\
+	if (SPLAY_RIGHT(elm, field) != NULL) {				\
+		elm = SPLAY_RIGHT(elm, field);				\
+		while (SPLAY_LEFT(elm, field) != NULL) {		\
+			elm = SPLAY_LEFT(elm, field);			\
+		}							\
+	} else								\
+		elm = NULL;						\
+	return (elm);							\
+}									\
+									\
+static __inline struct type *						\
+name##_SPLAY_MIN_MAX(struct name *head, int val)			\
+{									\
+	name##_SPLAY_MINMAX(head, val);					\
+        return (SPLAY_ROOT(head));					\
+}
+
+/* Main splay operation.
+ * Moves node close to the key of elm to top
+ */
+#define SPLAY_GENERATE(name, type, field, cmp)				\
+struct type *								\
+name##_SPLAY_INSERT(struct name *head, struct type *elm)		\
+{									\
+    if (SPLAY_EMPTY(head)) {						\
+	    SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL;	\
+    } else {								\
+	    int __comp;							\
+	    name##_SPLAY(head, elm);					\
+	    __comp = (cmp)(elm, (head)->sph_root);			\
+	    if(__comp < 0) {						\
+		    SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
+		    SPLAY_RIGHT(elm, field) = (head)->sph_root;		\
+		    SPLAY_LEFT((head)->sph_root, field) = NULL;		\
+	    } else if (__comp > 0) {					\
+		    SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
+		    SPLAY_LEFT(elm, field) = (head)->sph_root;		\
+		    SPLAY_RIGHT((head)->sph_root, field) = NULL;	\
+	    } else							\
+		    return ((head)->sph_root);				\
+    }									\
+    (head)->sph_root = (elm);						\
+    return (NULL);							\
+}									\
+									\
+struct type *								\
+name##_SPLAY_REMOVE(struct name *head, struct type *elm)		\
+{									\
+	struct type *__tmp;						\
+	if (SPLAY_EMPTY(head))						\
+		return (NULL);						\
+	name##_SPLAY(head, elm);					\
+	if ((cmp)(elm, (head)->sph_root) == 0) {			\
+		if (SPLAY_LEFT((head)->sph_root, field) == NULL) {	\
+			(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
+		} else {						\
+			__tmp = SPLAY_RIGHT((head)->sph_root, field);	\
+			(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
+			name##_SPLAY(head, elm);			\
+			SPLAY_RIGHT((head)->sph_root, field) = __tmp;	\
+		}							\
+		return (elm);						\
+	}								\
+	return (NULL);							\
+}									\
+									\
+void									\
+name##_SPLAY(struct name *head, struct type *elm)			\
+{									\
+	struct type __node, *__left, *__right, *__tmp;			\
+	int __comp;							\
+\
+	SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+	__left = __right = &__node;					\
+\
+	while ((__comp = (cmp)(elm, (head)->sph_root))) {		\
+		if (__comp < 0) {					\
+			__tmp = SPLAY_LEFT((head)->sph_root, field);	\
+			if (__tmp == NULL)				\
+				break;					\
+			if ((cmp)(elm, __tmp) < 0){			\
+				SPLAY_ROTATE_RIGHT(head, __tmp, field);	\
+				if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+					break;				\
+			}						\
+			SPLAY_LINKLEFT(head, __right, field);		\
+		} else if (__comp > 0) {				\
+			__tmp = SPLAY_RIGHT((head)->sph_root, field);	\
+			if (__tmp == NULL)				\
+				break;					\
+			if ((cmp)(elm, __tmp) > 0){			\
+				SPLAY_ROTATE_LEFT(head, __tmp, field);	\
+				if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+					break;				\
+			}						\
+			SPLAY_LINKRIGHT(head, __left, field);		\
+		}							\
+	}								\
+	SPLAY_ASSEMBLE(head, &__node, __left, __right, field);		\
+}									\
+									\
+/* Splay with either the minimum or the maximum element			\
+ * Used to find minimum or maximum element in tree.			\
+ */									\
+void name##_SPLAY_MINMAX(struct name *head, int __comp) \
+{									\
+	struct type __node, *__left, *__right, *__tmp;			\
+\
+	SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+	__left = __right = &__node;					\
+\
+	while (1) {							\
+		if (__comp < 0) {					\
+			__tmp = SPLAY_LEFT((head)->sph_root, field);	\
+			if (__tmp == NULL)				\
+				break;					\
+			if (__comp < 0){				\
+				SPLAY_ROTATE_RIGHT(head, __tmp, field);	\
+				if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+					break;				\
+			}						\
+			SPLAY_LINKLEFT(head, __right, field);		\
+		} else if (__comp > 0) {				\
+			__tmp = SPLAY_RIGHT((head)->sph_root, field);	\
+			if (__tmp == NULL)				\
+				break;					\
+			if (__comp > 0) {				\
+				SPLAY_ROTATE_LEFT(head, __tmp, field);	\
+				if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+					break;				\
+			}						\
+			SPLAY_LINKRIGHT(head, __left, field);		\
+		}							\
+	}								\
+	SPLAY_ASSEMBLE(head, &__node, __left, __right, field);		\
+}
+
+#define SPLAY_NEGINF	-1
+#define SPLAY_INF	1
+
+#define SPLAY_INSERT(name, x, y)	name##_SPLAY_INSERT(x, y)
+#define SPLAY_REMOVE(name, x, y)	name##_SPLAY_REMOVE(x, y)
+#define SPLAY_FIND(name, x, y)		name##_SPLAY_FIND(x, y)
+#define SPLAY_NEXT(name, x, y)		name##_SPLAY_NEXT(x, y)
+#define SPLAY_MIN(name, x)		(SPLAY_EMPTY(x) ? NULL	\
+					: name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
+#define SPLAY_MAX(name, x)		(SPLAY_EMPTY(x) ? NULL	\
+					: name##_SPLAY_MIN_MAX(x, SPLAY_INF))
+
+#define SPLAY_FOREACH(x, name, head)					\
+	for ((x) = SPLAY_MIN(name, head);				\
+	     (x) != NULL;						\
+	     (x) = SPLAY_NEXT(name, head, x))
+
+/* Macros that define a red-black tree */
+#define RB_HEAD(name, type)						\
+struct name {								\
+	struct type *rbh_root; /* root of the tree */			\
+}
+
+#define RB_INITIALIZER(root)						\
+	{ NULL }
+
+#define RB_INIT(root) do {						\
+	(root)->rbh_root = NULL;					\
+} while (0)
+
+#define RB_BLACK	0
+#define RB_RED		1
+#define RB_ENTRY(type)							\
+struct {								\
+	struct type *rbe_left;		/* left element */		\
+	struct type *rbe_right;		/* right element */		\
+	struct type *rbe_parent;	/* parent element */		\
+	int rbe_color;			/* node color */		\
+}
+
+#define RB_LEFT(elm, field)		(elm)->field.rbe_left
+#define RB_RIGHT(elm, field)		(elm)->field.rbe_right
+#define RB_PARENT(elm, field)		(elm)->field.rbe_parent
+#define RB_COLOR(elm, field)		(elm)->field.rbe_color
+#define RB_ROOT(head)			(head)->rbh_root
+#define RB_EMPTY(head)			(RB_ROOT(head) == NULL)
+
+#define RB_SET(elm, parent, field) do {					\
+	RB_PARENT(elm, field) = parent;					\
+	RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL;		\
+	RB_COLOR(elm, field) = RB_RED;					\
+} while (0)
+
+#define RB_SET_BLACKRED(black, red, field) do {				\
+	RB_COLOR(black, field) = RB_BLACK;				\
+	RB_COLOR(red, field) = RB_RED;					\
+} while (0)
+
+#ifndef RB_AUGMENT
+#define RB_AUGMENT(x)	do {} while (0)
+#endif
+
+#define RB_ROTATE_LEFT(head, elm, tmp, field) do {			\
+	(tmp) = RB_RIGHT(elm, field);					\
+	if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) {		\
+		RB_PARENT(RB_LEFT(tmp, field), field) = (elm);		\
+	}								\
+	RB_AUGMENT(elm);						\
+	if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {		\
+		if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))	\
+			RB_LEFT(RB_PARENT(elm, field), field) = (tmp);	\
+		else							\
+			RB_RIGHT(RB_PARENT(elm, field), field) = (tmp);	\
+	} else								\
+		(head)->rbh_root = (tmp);				\
+	RB_LEFT(tmp, field) = (elm);					\
+	RB_PARENT(elm, field) = (tmp);					\
+	RB_AUGMENT(tmp);						\
+	if ((RB_PARENT(tmp, field)))					\
+		RB_AUGMENT(RB_PARENT(tmp, field));			\
+} while (0)
+
+#define RB_ROTATE_RIGHT(head, elm, tmp, field) do {			\
+	(tmp) = RB_LEFT(elm, field);					\
+	if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) {		\
+		RB_PARENT(RB_RIGHT(tmp, field), field) = (elm);		\
+	}								\
+	RB_AUGMENT(elm);						\
+	if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {		\
+		if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))	\
+			RB_LEFT(RB_PARENT(elm, field), field) = (tmp);	\
+		else							\
+			RB_RIGHT(RB_PARENT(elm, field), field) = (tmp);	\
+	} else								\
+		(head)->rbh_root = (tmp);				\
+	RB_RIGHT(tmp, field) = (elm);					\
+	RB_PARENT(elm, field) = (tmp);					\
+	RB_AUGMENT(tmp);						\
+	if ((RB_PARENT(tmp, field)))					\
+		RB_AUGMENT(RB_PARENT(tmp, field));			\
+} while (0)
+
+/* Generates prototypes and inline functions */
+#define	RB_PROTOTYPE(name, type, field, cmp)				\
+	RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
+#define	RB_PROTOTYPE_STATIC(name, type, field, cmp)			\
+	RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __attribute__((__unused__)) static)
+#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr)		\
+attr void name##_RB_INSERT_COLOR(struct name *, struct type *);		\
+attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
+attr struct type *name##_RB_REMOVE(struct name *, struct type *);	\
+attr struct type *name##_RB_INSERT(struct name *, struct type *);	\
+attr struct type *name##_RB_FIND(struct name *, struct type *);		\
+attr struct type *name##_RB_NFIND(struct name *, struct type *);	\
+attr struct type *name##_RB_NEXT(struct type *);			\
+attr struct type *name##_RB_PREV(struct type *);			\
+attr struct type *name##_RB_MINMAX(struct name *, int);			\
+									\
+
+/* Main rb operation.
+ * Moves node close to the key of elm to top
+ */
+#define	RB_GENERATE(name, type, field, cmp)				\
+	RB_GENERATE_INTERNAL(name, type, field, cmp,)
+#define	RB_GENERATE_STATIC(name, type, field, cmp)			\
+	RB_GENERATE_INTERNAL(name, type, field, cmp, __attribute__((__unused__)) static)
+#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr)		\
+attr void								\
+name##_RB_INSERT_COLOR(struct name *head, struct type *elm)		\
+{									\
+	struct type *parent, *gparent, *tmp;				\
+	while ((parent = RB_PARENT(elm, field)) &&			\
+	    RB_COLOR(parent, field) == RB_RED) {			\
+		gparent = RB_PARENT(parent, field);			\
+		if (parent == RB_LEFT(gparent, field)) {		\
+			tmp = RB_RIGHT(gparent, field);			\
+			if (tmp && RB_COLOR(tmp, field) == RB_RED) {	\
+				RB_COLOR(tmp, field) = RB_BLACK;	\
+				RB_SET_BLACKRED(parent, gparent, field);\
+				elm = gparent;				\
+				continue;				\
+			}						\
+			if (RB_RIGHT(parent, field) == elm) {		\
+				RB_ROTATE_LEFT(head, parent, tmp, field);\
+				tmp = parent;				\
+				parent = elm;				\
+				elm = tmp;				\
+			}						\
+			RB_SET_BLACKRED(parent, gparent, field);	\
+			RB_ROTATE_RIGHT(head, gparent, tmp, field);	\
+		} else {						\
+			tmp = RB_LEFT(gparent, field);			\
+			if (tmp && RB_COLOR(tmp, field) == RB_RED) {	\
+				RB_COLOR(tmp, field) = RB_BLACK;	\
+				RB_SET_BLACKRED(parent, gparent, field);\
+				elm = gparent;				\
+				continue;				\
+			}						\
+			if (RB_LEFT(parent, field) == elm) {		\
+				RB_ROTATE_RIGHT(head, parent, tmp, field);\
+				tmp = parent;				\
+				parent = elm;				\
+				elm = tmp;				\
+			}						\
+			RB_SET_BLACKRED(parent, gparent, field);	\
+			RB_ROTATE_LEFT(head, gparent, tmp, field);	\
+		}							\
+	}								\
+	RB_COLOR(head->rbh_root, field) = RB_BLACK;			\
+}									\
+									\
+attr void								\
+name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
+{									\
+	struct type *tmp;						\
+	while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) &&	\
+	    elm != RB_ROOT(head)) {					\
+		if (RB_LEFT(parent, field) == elm) {			\
+			tmp = RB_RIGHT(parent, field);			\
+			if (RB_COLOR(tmp, field) == RB_RED) {		\
+				RB_SET_BLACKRED(tmp, parent, field);	\
+				RB_ROTATE_LEFT(head, parent, tmp, field);\
+				tmp = RB_RIGHT(parent, field);		\
+			}						\
+			if ((RB_LEFT(tmp, field) == NULL ||		\
+			    RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+			    (RB_RIGHT(tmp, field) == NULL ||		\
+			    RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+				RB_COLOR(tmp, field) = RB_RED;		\
+				elm = parent;				\
+				parent = RB_PARENT(elm, field);		\
+			} else {					\
+				if (RB_RIGHT(tmp, field) == NULL ||	\
+				    RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
+					struct type *oleft;		\
+					if ((oleft = RB_LEFT(tmp, field)))\
+						RB_COLOR(oleft, field) = RB_BLACK;\
+					RB_COLOR(tmp, field) = RB_RED;	\
+					RB_ROTATE_RIGHT(head, tmp, oleft, field);\
+					tmp = RB_RIGHT(parent, field);	\
+				}					\
+				RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+				RB_COLOR(parent, field) = RB_BLACK;	\
+				if (RB_RIGHT(tmp, field))		\
+					RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
+				RB_ROTATE_LEFT(head, parent, tmp, field);\
+				elm = RB_ROOT(head);			\
+				break;					\
+			}						\
+		} else {						\
+			tmp = RB_LEFT(parent, field);			\
+			if (RB_COLOR(tmp, field) == RB_RED) {		\
+				RB_SET_BLACKRED(tmp, parent, field);	\
+				RB_ROTATE_RIGHT(head, parent, tmp, field);\
+				tmp = RB_LEFT(parent, field);		\
+			}						\
+			if ((RB_LEFT(tmp, field) == NULL ||		\
+			    RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+			    (RB_RIGHT(tmp, field) == NULL ||		\
+			    RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+				RB_COLOR(tmp, field) = RB_RED;		\
+				elm = parent;				\
+				parent = RB_PARENT(elm, field);		\
+			} else {					\
+				if (RB_LEFT(tmp, field) == NULL ||	\
+				    RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
+					struct type *oright;		\
+					if ((oright = RB_RIGHT(tmp, field)))\
+						RB_COLOR(oright, field) = RB_BLACK;\
+					RB_COLOR(tmp, field) = RB_RED;	\
+					RB_ROTATE_LEFT(head, tmp, oright, field);\
+					tmp = RB_LEFT(parent, field);	\
+				}					\
+				RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+				RB_COLOR(parent, field) = RB_BLACK;	\
+				if (RB_LEFT(tmp, field))		\
+					RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
+				RB_ROTATE_RIGHT(head, parent, tmp, field);\
+				elm = RB_ROOT(head);			\
+				break;					\
+			}						\
+		}							\
+	}								\
+	if (elm)							\
+		RB_COLOR(elm, field) = RB_BLACK;			\
+}									\
+									\
+attr struct type *							\
+name##_RB_REMOVE(struct name *head, struct type *elm)			\
+{									\
+	struct type *child, *parent, *old = elm;			\
+	int color;							\
+	if (RB_LEFT(elm, field) == NULL)				\
+		child = RB_RIGHT(elm, field);				\
+	else if (RB_RIGHT(elm, field) == NULL)				\
+		child = RB_LEFT(elm, field);				\
+	else {								\
+		struct type *left;					\
+		elm = RB_RIGHT(elm, field);				\
+		while ((left = RB_LEFT(elm, field)))			\
+			elm = left;					\
+		child = RB_RIGHT(elm, field);				\
+		parent = RB_PARENT(elm, field);				\
+		color = RB_COLOR(elm, field);				\
+		if (child)						\
+			RB_PARENT(child, field) = parent;		\
+		if (parent) {						\
+			if (RB_LEFT(parent, field) == elm)		\
+				RB_LEFT(parent, field) = child;		\
+			else						\
+				RB_RIGHT(parent, field) = child;	\
+			RB_AUGMENT(parent);				\
+		} else							\
+			RB_ROOT(head) = child;				\
+		if (RB_PARENT(elm, field) == old)			\
+			parent = elm;					\
+		(elm)->field = (old)->field;				\
+		if (RB_PARENT(old, field)) {				\
+			if (RB_LEFT(RB_PARENT(old, field), field) == old)\
+				RB_LEFT(RB_PARENT(old, field), field) = elm;\
+			else						\
+				RB_RIGHT(RB_PARENT(old, field), field) = elm;\
+			RB_AUGMENT(RB_PARENT(old, field));		\
+		} else							\
+			RB_ROOT(head) = elm;				\
+		RB_PARENT(RB_LEFT(old, field), field) = elm;		\
+		if (RB_RIGHT(old, field))				\
+			RB_PARENT(RB_RIGHT(old, field), field) = elm;	\
+		if (parent) {						\
+			left = parent;					\
+			do {						\
+				RB_AUGMENT(left);			\
+			} while ((left = RB_PARENT(left, field)));	\
+		}							\
+		goto color;						\
+	}								\
+	parent = RB_PARENT(elm, field);					\
+	color = RB_COLOR(elm, field);					\
+	if (child)							\
+		RB_PARENT(child, field) = parent;			\
+	if (parent) {							\
+		if (RB_LEFT(parent, field) == elm)			\
+			RB_LEFT(parent, field) = child;			\
+		else							\
+			RB_RIGHT(parent, field) = child;		\
+		RB_AUGMENT(parent);					\
+	} else								\
+		RB_ROOT(head) = child;					\
+color:									\
+	if (color == RB_BLACK)						\
+		name##_RB_REMOVE_COLOR(head, parent, child);		\
+	return (old);							\
+}									\
+									\
+/* Inserts a node into the RB tree */					\
+attr struct type *							\
+name##_RB_INSERT(struct name *head, struct type *elm)			\
+{									\
+	struct type *tmp;						\
+	struct type *parent = NULL;					\
+	int comp = 0;							\
+	tmp = RB_ROOT(head);						\
+	while (tmp) {							\
+		parent = tmp;						\
+		comp = (cmp)(elm, parent);				\
+		if (comp < 0)						\
+			tmp = RB_LEFT(tmp, field);			\
+		else if (comp > 0)					\
+			tmp = RB_RIGHT(tmp, field);			\
+		else							\
+			return (tmp);					\
+	}								\
+	RB_SET(elm, parent, field);					\
+	if (parent != NULL) {						\
+		if (comp < 0)						\
+			RB_LEFT(parent, field) = elm;			\
+		else							\
+			RB_RIGHT(parent, field) = elm;			\
+		RB_AUGMENT(parent);					\
+	} else								\
+		RB_ROOT(head) = elm;					\
+	name##_RB_INSERT_COLOR(head, elm);				\
+	return (NULL);							\
+}									\
+									\
+/* Finds the node with the same key as elm */				\
+attr struct type *							\
+name##_RB_FIND(struct name *head, struct type *elm)			\
+{									\
+	struct type *tmp = RB_ROOT(head);				\
+	int comp;							\
+	while (tmp) {							\
+		comp = cmp(elm, tmp);					\
+		if (comp < 0)						\
+			tmp = RB_LEFT(tmp, field);			\
+		else if (comp > 0)					\
+			tmp = RB_RIGHT(tmp, field);			\
+		else							\
+			return (tmp);					\
+	}								\
+	return (NULL);							\
+}									\
+									\
+/* Finds the first node greater than or equal to the search key */	\
+attr struct type *							\
+name##_RB_NFIND(struct name *head, struct type *elm)			\
+{									\
+	struct type *tmp = RB_ROOT(head);				\
+	struct type *res = NULL;					\
+	int comp;							\
+	while (tmp) {							\
+		comp = cmp(elm, tmp);					\
+		if (comp < 0) {						\
+			res = tmp;					\
+			tmp = RB_LEFT(tmp, field);			\
+		}							\
+		else if (comp > 0)					\
+			tmp = RB_RIGHT(tmp, field);			\
+		else							\
+			return (tmp);					\
+	}								\
+	return (res);							\
+}									\
+									\
+/* ARGSUSED */								\
+attr struct type *							\
+name##_RB_NEXT(struct type *elm)					\
+{									\
+	if (RB_RIGHT(elm, field)) {					\
+		elm = RB_RIGHT(elm, field);				\
+		while (RB_LEFT(elm, field))				\
+			elm = RB_LEFT(elm, field);			\
+	} else {							\
+		if (RB_PARENT(elm, field) &&				\
+		    (elm == RB_LEFT(RB_PARENT(elm, field), field)))	\
+			elm = RB_PARENT(elm, field);			\
+		else {							\
+			while (RB_PARENT(elm, field) &&			\
+			    (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
+				elm = RB_PARENT(elm, field);		\
+			elm = RB_PARENT(elm, field);			\
+		}							\
+	}								\
+	return (elm);							\
+}									\
+									\
+/* ARGSUSED */								\
+attr struct type *							\
+name##_RB_PREV(struct type *elm)					\
+{									\
+	if (RB_LEFT(elm, field)) {					\
+		elm = RB_LEFT(elm, field);				\
+		while (RB_RIGHT(elm, field))				\
+			elm = RB_RIGHT(elm, field);			\
+	} else {							\
+		if (RB_PARENT(elm, field) &&				\
+		    (elm == RB_RIGHT(RB_PARENT(elm, field), field)))	\
+			elm = RB_PARENT(elm, field);			\
+		else {							\
+			while (RB_PARENT(elm, field) &&			\
+			    (elm == RB_LEFT(RB_PARENT(elm, field), field)))\
+				elm = RB_PARENT(elm, field);		\
+			elm = RB_PARENT(elm, field);			\
+		}							\
+	}								\
+	return (elm);							\
+}									\
+									\
+attr struct type *							\
+name##_RB_MINMAX(struct name *head, int val)				\
+{									\
+	struct type *tmp = RB_ROOT(head);				\
+	struct type *parent = NULL;					\
+	while (tmp) {							\
+		parent = tmp;						\
+		if (val < 0)						\
+			tmp = RB_LEFT(tmp, field);			\
+		else							\
+			tmp = RB_RIGHT(tmp, field);			\
+	}								\
+	return (parent);						\
+}
+
+#define RB_NEGINF	-1
+#define RB_INF	1
+
+#define RB_INSERT(name, x, y)	name##_RB_INSERT(x, y)
+#define RB_REMOVE(name, x, y)	name##_RB_REMOVE(x, y)
+#define RB_FIND(name, x, y)	name##_RB_FIND(x, y)
+#define RB_NFIND(name, x, y)	name##_RB_NFIND(x, y)
+#define RB_NEXT(name, x, y)	name##_RB_NEXT(y)
+#define RB_PREV(name, x, y)	name##_RB_PREV(y)
+#define RB_MIN(name, x)		name##_RB_MINMAX(x, RB_NEGINF)
+#define RB_MAX(name, x)		name##_RB_MINMAX(x, RB_INF)
+
+#define RB_FOREACH(x, name, head)					\
+	for ((x) = RB_MIN(name, head);					\
+	     (x) != NULL;						\
+	     (x) = name##_RB_NEXT(x))
+
+#define RB_FOREACH_SAFE(x, name, head, y)				\
+	for ((x) = RB_MIN(name, head);					\
+	    ((x) != NULL) && ((y) = name##_RB_NEXT(x), 1);		\
+	     (x) = (y))
+
+#define RB_FOREACH_REVERSE(x, name, head)				\
+	for ((x) = RB_MAX(name, head);					\
+	     (x) != NULL;						\
+	     (x) = name##_RB_PREV(x))
+
+#define RB_FOREACH_REVERSE_SAFE(x, name, head, y)			\
+	for ((x) = RB_MAX(name, head);					\
+	    ((x) != NULL) && ((y) = name##_RB_PREV(x), 1);		\
+	     (x) = (y))
+
+#endif	/* _SYS_TREE_H_ */
\ No newline at end of file


Property changes on: trunk/usr.bin/doas/tree.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+MidnightBSD=%H
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/plain
\ No newline at end of property


More information about the Midnightbsd-cvs mailing list