Home | History | Annotate | Line # | Download | only in dist
      1 /*	$NetBSD: misc.c,v 1.41 2026/04/08 18:58:40 christos Exp $	*/
      2 /* $OpenBSD: misc.c,v 1.213 2026/03/03 09:57:25 dtucker Exp $ */
      3 
      4 /*
      5  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
      6  * Copyright (c) 2005-2020 Damien Miller.  All rights reserved.
      7  * Copyright (c) 2004 Henning Brauer <henning (at) openbsd.org>
      8  *
      9  * Permission to use, copy, modify, and distribute this software for any
     10  * purpose with or without fee is hereby granted, provided that the above
     11  * copyright notice and this permission notice appear in all copies.
     12  *
     13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     20  */
     21 
     22 #include "includes.h"
     23 __RCSID("$NetBSD: misc.c,v 1.41 2026/04/08 18:58:40 christos Exp $");
     24 
     25 #include <sys/types.h>
     26 #include <sys/ioctl.h>
     27 #include <sys/mman.h>
     28 #include <sys/socket.h>
     29 #include <sys/stat.h>
     30 #include <sys/time.h>
     31 #include <sys/wait.h>
     32 #include <sys/un.h>
     33 
     34 #include <net/if.h>
     35 #include <net/if_tun.h>
     36 #include <netinet/in.h>
     37 #include <netinet/ip.h>
     38 #include <netinet/tcp.h>
     39 #include <arpa/inet.h>
     40 
     41 #include <ctype.h>
     42 #include <errno.h>
     43 #include <fcntl.h>
     44 #include <netdb.h>
     45 #include <paths.h>
     46 #include <pwd.h>
     47 #include <libgen.h>
     48 #include <limits.h>
     49 #include <nlist.h>
     50 #include <poll.h>
     51 #include <signal.h>
     52 #include <stdarg.h>
     53 #include <stdio.h>
     54 #include <stdint.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <time.h>
     58 #include <unistd.h>
     59 
     60 #include "xmalloc.h"
     61 #include "misc.h"
     62 #include "log.h"
     63 #include "ssh.h"
     64 #include "sshbuf.h"
     65 #include "ssherr.h"
     66 
     67 /* remove newline at end of string */
     68 char *
     69 chop(char *s)
     70 {
     71 	char *t = s;
     72 	while (*t) {
     73 		if (*t == '\n' || *t == '\r') {
     74 			*t = '\0';
     75 			return s;
     76 		}
     77 		t++;
     78 	}
     79 	return s;
     80 
     81 }
     82 
     83 /* remove whitespace from end of string */
     84 void
     85 rtrim(char *s)
     86 {
     87 	size_t i;
     88 
     89 	if ((i = strlen(s)) == 0)
     90 		return;
     91 	do {
     92 		i--;
     93 		if (isspace((unsigned char)s[i]))
     94 			s[i] = '\0';
     95 		else
     96 			break;
     97 	} while (i > 0);
     98 }
     99 
    100 /*
    101  * returns pointer to character after 'prefix' in 's' or otherwise NULL
    102  * if the prefix is not present.
    103  */
    104 const char *
    105 strprefix(const char *s, const char *prefix, int ignorecase)
    106 {
    107 	size_t prefixlen;
    108 
    109 	if ((prefixlen = strlen(prefix)) == 0)
    110 		return s;
    111 	if (ignorecase) {
    112 		if (strncasecmp(s, prefix, prefixlen) != 0)
    113 			return NULL;
    114 	} else {
    115 		if (strncmp(s, prefix, prefixlen) != 0)
    116 			return NULL;
    117 	}
    118 	return s + prefixlen;
    119 }
    120 
    121 /* Append string 's' to a NULL-terminated array of strings */
    122 void
    123 stringlist_append(char ***listp, const char *s)
    124 {
    125 	size_t i = 0;
    126 
    127 	if (*listp == NULL)
    128 		*listp = xcalloc(2, sizeof(**listp));
    129 	else {
    130 		for (i = 0; (*listp)[i] != NULL; i++)
    131 			; /* count */
    132 		*listp = xrecallocarray(*listp, i + 1, i + 2, sizeof(**listp));
    133 	}
    134 	(*listp)[i] = xstrdup(s);
    135 }
    136 
    137 void
    138 stringlist_free(char **list)
    139 {
    140 	size_t i = 0;
    141 
    142 	if (list == NULL)
    143 		return;
    144 	for (i = 0; list[i] != NULL; i++)
    145 		free(list[i]);
    146 	free(list);
    147 }
    148 
    149 /* set/unset filedescriptor to non-blocking */
    150 int
    151 set_nonblock(int fd)
    152 {
    153 	int val;
    154 
    155 	val = fcntl(fd, F_GETFL);
    156 	if (val == -1) {
    157 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
    158 		return (-1);
    159 	}
    160 	if (val & O_NONBLOCK) {
    161 		debug3("fd %d is O_NONBLOCK", fd);
    162 		return (0);
    163 	}
    164 	debug2("fd %d setting O_NONBLOCK", fd);
    165 	val |= O_NONBLOCK;
    166 	if (fcntl(fd, F_SETFL, val) == -1) {
    167 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
    168 		    strerror(errno));
    169 		return (-1);
    170 	}
    171 	return (0);
    172 }
    173 
    174 int
    175 unset_nonblock(int fd)
    176 {
    177 	int val;
    178 
    179 	val = fcntl(fd, F_GETFL);
    180 	if (val == -1) {
    181 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
    182 		return (-1);
    183 	}
    184 	if (!(val & O_NONBLOCK)) {
    185 		debug3("fd %d is not O_NONBLOCK", fd);
    186 		return (0);
    187 	}
    188 	debug("fd %d clearing O_NONBLOCK", fd);
    189 	val &= ~O_NONBLOCK;
    190 	if (fcntl(fd, F_SETFL, val) == -1) {
    191 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
    192 		    fd, strerror(errno));
    193 		return (-1);
    194 	}
    195 	return (0);
    196 }
    197 
    198 const char *
    199 ssh_gai_strerror(int gaierr)
    200 {
    201 	if (gaierr == EAI_SYSTEM && errno != 0)
    202 		return strerror(errno);
    203 	return gai_strerror(gaierr);
    204 }
    205 
    206 /* disable nagle on socket */
    207 void
    208 set_nodelay(int fd)
    209 {
    210 	int opt;
    211 	socklen_t optlen;
    212 
    213 	optlen = sizeof opt;
    214 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
    215 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
    216 		return;
    217 	}
    218 	if (opt == 1) {
    219 		debug2("fd %d is TCP_NODELAY", fd);
    220 		return;
    221 	}
    222 	opt = 1;
    223 	debug2("fd %d setting TCP_NODELAY", fd);
    224 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
    225 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
    226 }
    227 
    228 /* Allow local port reuse in TIME_WAIT */
    229 int
    230 set_reuseaddr(int fd)
    231 {
    232 	int on = 1;
    233 
    234 	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
    235 		error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
    236 		return -1;
    237 	}
    238 	return 0;
    239 }
    240 
    241 /* Get/set routing domain */
    242 char *
    243 get_rdomain(int fd)
    244 {
    245 #ifdef SO_RTABLE
    246 	int rtable;
    247 	char *ret;
    248 	socklen_t len = sizeof(rtable);
    249 
    250 	if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
    251 		error("Failed to get routing domain for fd %d: %s",
    252 		    fd, strerror(errno));
    253 		return NULL;
    254 	}
    255 	xasprintf(&ret, "%d", rtable);
    256 	return ret;
    257 #else
    258 	return NULL;
    259 #endif
    260 }
    261 
    262 int
    263 set_rdomain(int fd, const char *name)
    264 {
    265 #ifdef SO_RTABLE
    266 	int rtable;
    267 	const char *errstr;
    268 
    269 	if (name == NULL)
    270 		return 0; /* default table */
    271 
    272 	rtable = (int)strtonum(name, 0, 255, &errstr);
    273 	if (errstr != NULL) {
    274 		/* Shouldn't happen */
    275 		error("Invalid routing domain \"%s\": %s", name, errstr);
    276 		return -1;
    277 	}
    278 	if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
    279 	    &rtable, sizeof(rtable)) == -1) {
    280 		error("Failed to set routing domain %d on fd %d: %s",
    281 		    rtable, fd, strerror(errno));
    282 		return -1;
    283 	}
    284 	return 0;
    285 #else
    286 	return -1;
    287 #endif
    288 }
    289 
    290 int
    291 get_sock_af(int fd)
    292 {
    293 	struct sockaddr_storage to;
    294 	socklen_t tolen = sizeof(to);
    295 
    296 	memset(&to, 0, sizeof(to));
    297 	if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
    298 		return -1;
    299 	return to.ss_family;
    300 }
    301 
    302 void
    303 set_sock_tos(int fd, int tos)
    304 {
    305 	int af;
    306 
    307 	if (tos < 0 || tos == INT_MAX) {
    308 		debug_f("invalid TOS %d", tos);
    309 		return;
    310 	}
    311 	switch ((af = get_sock_af(fd))) {
    312 	case -1:
    313 		/* assume not a socket */
    314 		break;
    315 	case AF_INET:
    316 		debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
    317 		if (setsockopt(fd, IPPROTO_IP, IP_TOS,
    318 		    &tos, sizeof(tos)) == -1) {
    319 			error("setsockopt socket %d IP_TOS %d: %s",
    320 			    fd, tos, strerror(errno));
    321 		}
    322 		break;
    323 	case AF_INET6:
    324 		debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
    325 		if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
    326 		    &tos, sizeof(tos)) == -1) {
    327 			error("setsockopt socket %d IPV6_TCLASS %d: %s",
    328 			    fd, tos, strerror(errno));
    329 		}
    330 		break;
    331 	default:
    332 		debug2_f("unsupported socket family %d", af);
    333 		break;
    334 	}
    335 }
    336 
    337 /*
    338  * Wait up to *timeoutp milliseconds for events on fd. Updates
    339  * *timeoutp with time remaining.
    340  * Returns 0 if fd ready or -1 on timeout or error (see errno).
    341  */
    342 static int
    343 waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
    344 {
    345 	struct pollfd pfd;
    346 	struct timespec timeout;
    347 	int oerrno, r;
    348 	sigset_t nsigset, osigset;
    349 
    350 	if (timeoutp && *timeoutp == -1)
    351 		timeoutp = NULL;
    352 	pfd.fd = fd;
    353 	pfd.events = events;
    354 	ptimeout_init(&timeout);
    355 	if (timeoutp != NULL)
    356 		ptimeout_deadline_ms(&timeout, *timeoutp);
    357 	if (stop != NULL)
    358 		sigfillset(&nsigset);
    359 	for (; timeoutp == NULL || *timeoutp >= 0;) {
    360 		if (stop != NULL) {
    361 			sigprocmask(SIG_BLOCK, &nsigset, &osigset);
    362 			if (*stop) {
    363 				sigprocmask(SIG_SETMASK, &osigset, NULL);
    364 				errno = EINTR;
    365 				return -1;
    366 			}
    367 		}
    368 		r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
    369 		    stop != NULL ? &osigset : NULL);
    370 		oerrno = errno;
    371 		if (stop != NULL)
    372 			sigprocmask(SIG_SETMASK, &osigset, NULL);
    373 		if (timeoutp)
    374 			*timeoutp = ptimeout_get_ms(&timeout);
    375 		errno = oerrno;
    376 		if (r > 0)
    377 			return 0;
    378 		else if (r == -1 && errno != EAGAIN && errno != EINTR)
    379 			return -1;
    380 		else if (r == 0)
    381 			break;
    382 	}
    383 	/* timeout */
    384 	errno = ETIMEDOUT;
    385 	return -1;
    386 }
    387 
    388 /*
    389  * Wait up to *timeoutp milliseconds for fd to be readable. Updates
    390  * *timeoutp with time remaining.
    391  * Returns 0 if fd ready or -1 on timeout or error (see errno).
    392  */
    393 int
    394 waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
    395 	return waitfd(fd, timeoutp, POLLIN, stop);
    396 }
    397 
    398 /*
    399  * Attempt a non-blocking connect(2) to the specified address, waiting up to
    400  * *timeoutp milliseconds for the connection to complete. If the timeout is
    401  * <=0, then wait indefinitely.
    402  *
    403  * Returns 0 on success or -1 on failure.
    404  */
    405 int
    406 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
    407     socklen_t addrlen, int *timeoutp)
    408 {
    409 	int optval = 0;
    410 	socklen_t optlen = sizeof(optval);
    411 
    412 	/* No timeout: just do a blocking connect() */
    413 	if (timeoutp == NULL || *timeoutp <= 0)
    414 		return connect(sockfd, serv_addr, addrlen);
    415 
    416 	set_nonblock(sockfd);
    417 	for (;;) {
    418 		if (connect(sockfd, serv_addr, addrlen) == 0) {
    419 			/* Succeeded already? */
    420 			unset_nonblock(sockfd);
    421 			return 0;
    422 		} else if (errno == EINTR)
    423 			continue;
    424 		else if (errno != EINPROGRESS)
    425 			return -1;
    426 		break;
    427 	}
    428 
    429 	if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
    430 		return -1;
    431 
    432 	/* Completed or failed */
    433 	if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
    434 		debug("getsockopt: %s", strerror(errno));
    435 		return -1;
    436 	}
    437 	if (optval != 0) {
    438 		errno = optval;
    439 		return -1;
    440 	}
    441 	unset_nonblock(sockfd);
    442 	return 0;
    443 }
    444 
    445 /* Characters considered whitespace in strsep calls. */
    446 #define WHITESPACE " \t\r\n"
    447 #define QUOTE	"\""
    448 
    449 /* return next token in configuration line */
    450 static char *
    451 strdelim_internal(char **s, int split_equals)
    452 {
    453 	char *old;
    454 	int wspace = 0;
    455 
    456 	if (*s == NULL)
    457 		return NULL;
    458 
    459 	old = *s;
    460 
    461 	*s = strpbrk(*s,
    462 	    split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
    463 	if (*s == NULL)
    464 		return (old);
    465 
    466 	if (*s[0] == '\"') {
    467 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
    468 		/* Find matching quote */
    469 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
    470 			return (NULL);		/* no matching quote */
    471 		} else {
    472 			*s[0] = '\0';
    473 			*s += strspn(*s + 1, WHITESPACE) + 1;
    474 			return (old);
    475 		}
    476 	}
    477 
    478 	/* Allow only one '=' to be skipped */
    479 	if (split_equals && *s[0] == '=')
    480 		wspace = 1;
    481 	*s[0] = '\0';
    482 
    483 	/* Skip any extra whitespace after first token */
    484 	*s += strspn(*s + 1, WHITESPACE) + 1;
    485 	if (split_equals && *s[0] == '=' && !wspace)
    486 		*s += strspn(*s + 1, WHITESPACE) + 1;
    487 
    488 	return (old);
    489 }
    490 
    491 /*
    492  * Return next token in configuration line; splits on whitespace or a
    493  * single '=' character.
    494  */
    495 char *
    496 strdelim(char **s)
    497 {
    498 	return strdelim_internal(s, 1);
    499 }
    500 
    501 /*
    502  * Return next token in configuration line; splits on whitespace only.
    503  */
    504 char *
    505 strdelimw(char **s)
    506 {
    507 	return strdelim_internal(s, 0);
    508 }
    509 
    510 struct passwd *
    511 pwcopy(struct passwd *pw)
    512 {
    513 	struct passwd *copy = xcalloc(1, sizeof(*copy));
    514 
    515 	copy->pw_name = xstrdup(pw->pw_name);
    516 	copy->pw_passwd = xstrdup(pw->pw_passwd);
    517 	copy->pw_gecos = xstrdup(pw->pw_gecos);
    518 	copy->pw_uid = pw->pw_uid;
    519 	copy->pw_gid = pw->pw_gid;
    520 	copy->pw_expire = pw->pw_expire;
    521 	copy->pw_change = pw->pw_change;
    522 	copy->pw_class = xstrdup(pw->pw_class);
    523 	copy->pw_dir = xstrdup(pw->pw_dir);
    524 	copy->pw_shell = xstrdup(pw->pw_shell);
    525 	return copy;
    526 }
    527 
    528 void
    529 pwfree(struct passwd *pw)
    530 {
    531 	if (pw == NULL)
    532 		return;
    533 	free(pw->pw_name);
    534 	freezero(pw->pw_passwd,
    535 	    pw->pw_passwd == NULL ? 0 : strlen(pw->pw_passwd));
    536 	free(pw->pw_gecos);
    537 	free(pw->pw_class);
    538 	free(pw->pw_dir);
    539 	free(pw->pw_shell);
    540 	freezero(pw, sizeof(*pw));
    541 }
    542 
    543 /*
    544  * Convert ASCII string to TCP/IP port number.
    545  * Port must be >=0 and <=65535.
    546  * Return -1 if invalid.
    547  */
    548 int
    549 a2port(const char *s)
    550 {
    551 	struct servent *se;
    552 	long long port;
    553 	const char *errstr;
    554 
    555 	port = strtonum(s, 0, 65535, &errstr);
    556 	if (errstr == NULL)
    557 		return (int)port;
    558 	if ((se = getservbyname(s, "tcp")) != NULL)
    559 		return ntohs(se->s_port);
    560 	return -1;
    561 }
    562 
    563 int
    564 a2tun(const char *s, int *remote)
    565 {
    566 	const char *errstr = NULL;
    567 	char *sp, *ep;
    568 	int tun;
    569 
    570 	if (remote != NULL) {
    571 		*remote = SSH_TUNID_ANY;
    572 		sp = xstrdup(s);
    573 		if ((ep = strchr(sp, ':')) == NULL) {
    574 			free(sp);
    575 			return (a2tun(s, NULL));
    576 		}
    577 		ep[0] = '\0'; ep++;
    578 		*remote = a2tun(ep, NULL);
    579 		tun = a2tun(sp, NULL);
    580 		free(sp);
    581 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
    582 	}
    583 
    584 	if (strcasecmp(s, "any") == 0)
    585 		return (SSH_TUNID_ANY);
    586 
    587 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
    588 	if (errstr != NULL)
    589 		return (SSH_TUNID_ERR);
    590 
    591 	return (tun);
    592 }
    593 
    594 #define SECONDS		1.0
    595 #define MINUTES		(SECONDS * 60)
    596 #define HOURS		(MINUTES * 60)
    597 #define DAYS		(HOURS * 24)
    598 #define WEEKS		(DAYS * 7)
    599 
    600 /*
    601  * Convert an interval/duration time string into seconds, which may include
    602  * fractional seconds.
    603  *
    604  * The format is a sequence of:
    605  *      time[qualifier]
    606  *
    607  * This supports fractional values for the seconds value only. All other
    608  * values must be integers.
    609  *
    610  * Valid time qualifiers are:
    611  *      <none>  seconds
    612  *      s|S     seconds
    613  *      m|M     minutes
    614  *      h|H     hours
    615  *      d|D     days
    616  *      w|W     weeks
    617  *
    618  * Examples:
    619  *      90m      90 minutes
    620  *      1h30m    90 minutes
    621  *      1.5s     1.5 seconds
    622  *      2d       2 days
    623  *      1w       1 week
    624  *
    625  * Returns <0.0 if the time string is invalid.
    626  */
    627 double
    628 convtime_double(const char *s)
    629 {
    630 	double val, total_sec = 0.0, multiplier;
    631 	const char *p, *start_p;
    632 	char *endp;
    633 	int seen_seconds = 0;
    634 
    635 	if (s == NULL || *s == '\0')
    636 		return -1.0;
    637 
    638 	for (p = s; *p != '\0';) {
    639 		if (!isdigit((unsigned char)*p) && *p != '.')
    640 			return -1.0;
    641 
    642 		errno = 0;
    643 		if ((val = strtod(p, &endp)) < 0 || errno != 0 || p == endp)
    644 			return -1.0;
    645 		/* Allow only decimal forms */
    646 		if (p + strspn(p, "0123456789.") != endp)
    647 			return -1.0;
    648 		start_p = p;
    649 		p = endp;
    650 
    651 		switch (*p) {
    652 		case '\0':
    653 			/* FALLTHROUGH */
    654 		case 's':
    655 		case 'S':
    656 			if (seen_seconds++)
    657 				return -1.0;
    658 			multiplier = SECONDS;
    659 			break;
    660 		case 'm':
    661 		case 'M':
    662 			multiplier = MINUTES;
    663 			break;
    664 		case 'h':
    665 		case 'H':
    666 			multiplier = HOURS;
    667 			break;
    668 		case 'd':
    669 		case 'D':
    670 			multiplier = DAYS;
    671 			break;
    672 		case 'w':
    673 		case 'W':
    674 			multiplier = WEEKS;
    675 			break;
    676 		default:
    677 			return -1.0;
    678 		}
    679 
    680 		/* Special handling if this was a decimal */
    681 		if (memchr(start_p, '.', endp - start_p) != NULL) {
    682 			/* Decimal point present */
    683 			if (multiplier > 1.0)
    684 				return -1.0; /* No fractionals for non-seconds */
    685 			/* For seconds, ensure digits follow */
    686 			if (!isdigit((unsigned char)*(endp - 1)))
    687 				return -1.0;
    688 		}
    689 
    690 		total_sec += val * multiplier;
    691 
    692 		if (*p != '\0')
    693 			p++;
    694 	}
    695 	return total_sec;
    696 }
    697 
    698 /*
    699  * Same as convtime_double() above but fractional seconds are ignored.
    700  * Return -1 if time string is invalid.
    701  */
    702 int
    703 convtime(const char *s)
    704 {
    705 	double sec_val;
    706 
    707 	if ((sec_val = convtime_double(s)) < 0.0)
    708 		return -1;
    709 
    710 	/* Check for overflow into int */
    711 	if (sec_val < 0 || sec_val > INT_MAX)
    712 		return -1;
    713 
    714 	return (int)sec_val;
    715 }
    716 
    717 #define TF_BUFS	8
    718 #define TF_LEN	21
    719 
    720 const char *
    721 fmt_timeframe(time_t t)
    722 {
    723 	char		*buf;
    724 	static char	 tfbuf[TF_BUFS][TF_LEN];	/* ring buffer */
    725 	static int	 idx = 0;
    726 	unsigned int	 sec, min, hrs, day;
    727 	unsigned long long	week;
    728 
    729 	buf = tfbuf[idx++];
    730 	if (idx == TF_BUFS)
    731 		idx = 0;
    732 
    733 	week = t;
    734 
    735 	sec = week % 60;
    736 	week /= 60;
    737 	min = week % 60;
    738 	week /= 60;
    739 	hrs = week % 24;
    740 	week /= 24;
    741 	day = week % 7;
    742 	week /= 7;
    743 
    744 	if (week > 0)
    745 		snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
    746 	else if (day > 0)
    747 		snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
    748 	else
    749 		snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
    750 
    751 	return (buf);
    752 }
    753 
    754 /*
    755  * Returns a standardized host+port identifier string.
    756  * Caller must free returned string.
    757  */
    758 char *
    759 put_host_port(const char *host, u_short port)
    760 {
    761 	char *hoststr;
    762 
    763 	if (port == 0 || port == SSH_DEFAULT_PORT)
    764 		return(xstrdup(host));
    765 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
    766 		fatal("put_host_port: asprintf: %s", strerror(errno));
    767 	debug3("put_host_port: %s", hoststr);
    768 	return hoststr;
    769 }
    770 
    771 /*
    772  * Search for next delimiter between hostnames/addresses and ports.
    773  * Argument may be modified (for termination).
    774  * Returns *cp if parsing succeeds.
    775  * *cp is set to the start of the next field, if one was found.
    776  * The delimiter char, if present, is stored in delim.
    777  * If this is the last field, *cp is set to NULL.
    778  */
    779 char *
    780 hpdelim2(char **cp, char *delim)
    781 {
    782 	char *s, *old;
    783 
    784 	if (cp == NULL || *cp == NULL)
    785 		return NULL;
    786 
    787 	old = s = *cp;
    788 	if (*s == '[') {
    789 		if ((s = strchr(s, ']')) == NULL)
    790 			return NULL;
    791 		else
    792 			s++;
    793 	} else if ((s = strpbrk(s, ":/")) == NULL)
    794 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
    795 
    796 	switch (*s) {
    797 	case '\0':
    798 		*cp = NULL;	/* no more fields*/
    799 		break;
    800 
    801 	case ':':
    802 	case '/':
    803 		if (delim != NULL)
    804 			*delim = *s;
    805 		*s = '\0';	/* terminate */
    806 		*cp = s + 1;
    807 		break;
    808 
    809 	default:
    810 		return NULL;
    811 	}
    812 
    813 	return old;
    814 }
    815 
    816 /* The common case: only accept colon as delimiter. */
    817 char *
    818 hpdelim(char **cp)
    819 {
    820 	char *r, delim = '\0';
    821 
    822 	r =  hpdelim2(cp, &delim);
    823 	if (delim == '/')
    824 		return NULL;
    825 	return r;
    826 }
    827 
    828 char *
    829 cleanhostname(char *host)
    830 {
    831 	if (*host == '[' && host[strlen(host) - 1] == ']') {
    832 		host[strlen(host) - 1] = '\0';
    833 		return (host + 1);
    834 	} else
    835 		return host;
    836 }
    837 
    838 char *
    839 colon(char *cp)
    840 {
    841 	int flag = 0;
    842 
    843 	if (*cp == ':')		/* Leading colon is part of file name. */
    844 		return NULL;
    845 	if (*cp == '[')
    846 		flag = 1;
    847 
    848 	for (; *cp; ++cp) {
    849 		if (*cp == '@' && *(cp+1) == '[')
    850 			flag = 1;
    851 		if (*cp == ']' && *(cp+1) == ':' && flag)
    852 			return (cp+1);
    853 		if (*cp == ':' && !flag)
    854 			return (cp);
    855 		if (*cp == '/')
    856 			return NULL;
    857 	}
    858 	return NULL;
    859 }
    860 
    861 /*
    862  * Parse a [user@]host:[path] string.
    863  * Caller must free returned user, host and path.
    864  * Any of the pointer return arguments may be NULL (useful for syntax checking).
    865  * If user was not specified then *userp will be set to NULL.
    866  * If host was not specified then *hostp will be set to NULL.
    867  * If path was not specified then *pathp will be set to ".".
    868  * Returns 0 on success, -1 on failure.
    869  */
    870 int
    871 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
    872 {
    873 	char *user = NULL, *host = NULL, *path = NULL;
    874 	char *sdup, *tmp;
    875 	int ret = -1;
    876 
    877 	if (userp != NULL)
    878 		*userp = NULL;
    879 	if (hostp != NULL)
    880 		*hostp = NULL;
    881 	if (pathp != NULL)
    882 		*pathp = NULL;
    883 
    884 	sdup = xstrdup(s);
    885 
    886 	/* Check for remote syntax: [user@]host:[path] */
    887 	if ((tmp = colon(sdup)) == NULL)
    888 		goto out;
    889 
    890 	/* Extract optional path */
    891 	*tmp++ = '\0';
    892 	if (*tmp == '\0')
    893 		tmp = __UNCONST(".");
    894 	path = xstrdup(tmp);
    895 
    896 	/* Extract optional user and mandatory host */
    897 	tmp = strrchr(sdup, '@');
    898 	if (tmp != NULL) {
    899 		*tmp++ = '\0';
    900 		host = xstrdup(cleanhostname(tmp));
    901 		if (*sdup != '\0')
    902 			user = xstrdup(sdup);
    903 	} else {
    904 		host = xstrdup(cleanhostname(sdup));
    905 		user = NULL;
    906 	}
    907 
    908 	/* Success */
    909 	if (userp != NULL) {
    910 		*userp = user;
    911 		user = NULL;
    912 	}
    913 	if (hostp != NULL) {
    914 		*hostp = host;
    915 		host = NULL;
    916 	}
    917 	if (pathp != NULL) {
    918 		*pathp = path;
    919 		path = NULL;
    920 	}
    921 	ret = 0;
    922 out:
    923 	free(sdup);
    924 	free(user);
    925 	free(host);
    926 	free(path);
    927 	return ret;
    928 }
    929 
    930 /*
    931  * Parse a [user@]host[:port] string.
    932  * Caller must free returned user and host.
    933  * Any of the pointer return arguments may be NULL (useful for syntax checking).
    934  * If user was not specified then *userp will be set to NULL.
    935  * If port was not specified then *portp will be -1.
    936  * Returns 0 on success, -1 on failure.
    937  */
    938 int
    939 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
    940 {
    941 	char *sdup, *cp, *tmp;
    942 	char *user = NULL, *host = NULL;
    943 	int port = -1, ret = -1;
    944 
    945 	if (userp != NULL)
    946 		*userp = NULL;
    947 	if (hostp != NULL)
    948 		*hostp = NULL;
    949 	if (portp != NULL)
    950 		*portp = -1;
    951 
    952 	if ((sdup = tmp = strdup(s)) == NULL)
    953 		return -1;
    954 	/* Extract optional username */
    955 	if ((cp = strrchr(tmp, '@')) != NULL) {
    956 		*cp = '\0';
    957 		if (*tmp == '\0')
    958 			goto out;
    959 		if ((user = strdup(tmp)) == NULL)
    960 			goto out;
    961 		tmp = cp + 1;
    962 	}
    963 	/* Extract mandatory hostname */
    964 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
    965 		goto out;
    966 	host = xstrdup(cleanhostname(cp));
    967 	/* Convert and verify optional port */
    968 	if (tmp != NULL && *tmp != '\0') {
    969 		if ((port = a2port(tmp)) <= 0)
    970 			goto out;
    971 	}
    972 	/* Success */
    973 	if (userp != NULL) {
    974 		*userp = user;
    975 		user = NULL;
    976 	}
    977 	if (hostp != NULL) {
    978 		*hostp = host;
    979 		host = NULL;
    980 	}
    981 	if (portp != NULL)
    982 		*portp = port;
    983 	ret = 0;
    984  out:
    985 	free(sdup);
    986 	free(user);
    987 	free(host);
    988 	return ret;
    989 }
    990 
    991 /*
    992  * Converts a two-byte hex string to decimal.
    993  * Returns the decimal value or -1 for invalid input.
    994  */
    995 static int
    996 hexchar(const char *s)
    997 {
    998 	unsigned char result[2];
    999 	int i;
   1000 
   1001 	for (i = 0; i < 2; i++) {
   1002 		if (s[i] >= '0' && s[i] <= '9')
   1003 			result[i] = (unsigned char)(s[i] - '0');
   1004 		else if (s[i] >= 'a' && s[i] <= 'f')
   1005 			result[i] = (unsigned char)(s[i] - 'a') + 10;
   1006 		else if (s[i] >= 'A' && s[i] <= 'F')
   1007 			result[i] = (unsigned char)(s[i] - 'A') + 10;
   1008 		else
   1009 			return -1;
   1010 	}
   1011 	return (result[0] << 4) | result[1];
   1012 }
   1013 
   1014 /*
   1015  * Decode an url-encoded string.
   1016  * Returns a newly allocated string on success or NULL on failure.
   1017  */
   1018 static char *
   1019 urldecode(const char *src)
   1020 {
   1021 	char *ret, *dst;
   1022 	int ch;
   1023 	size_t srclen;
   1024 
   1025 	if ((srclen = strlen(src)) >= SIZE_MAX)
   1026 		return NULL;
   1027 	ret = xmalloc(srclen + 1);
   1028 	for (dst = ret; *src != '\0'; src++) {
   1029 		switch (*src) {
   1030 		case '+':
   1031 			*dst++ = ' ';
   1032 			break;
   1033 		case '%':
   1034 			/* note: don't allow \0 characters */
   1035 			if (!isxdigit((unsigned char)src[1]) ||
   1036 			    !isxdigit((unsigned char)src[2]) ||
   1037 			    (ch = hexchar(src + 1)) == -1 || ch == 0) {
   1038 				free(ret);
   1039 				return NULL;
   1040 			}
   1041 			*dst++ = ch;
   1042 			src += 2;
   1043 			break;
   1044 		default:
   1045 			*dst++ = *src;
   1046 			break;
   1047 		}
   1048 	}
   1049 	*dst = '\0';
   1050 
   1051 	return ret;
   1052 }
   1053 
   1054 /*
   1055  * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
   1056  * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
   1057  * Either user or path may be url-encoded (but not host or port).
   1058  * Caller must free returned user, host and path.
   1059  * Any of the pointer return arguments may be NULL (useful for syntax checking)
   1060  * but the scheme must always be specified.
   1061  * If user was not specified then *userp will be set to NULL.
   1062  * If port was not specified then *portp will be -1.
   1063  * If path was not specified then *pathp will be set to NULL.
   1064  * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
   1065  */
   1066 int
   1067 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
   1068     int *portp, char **pathp)
   1069 {
   1070 	char *uridup, *cp, *tmp, ch;
   1071 	char *user = NULL, *host = NULL, *path = NULL;
   1072 	int port = -1, ret = -1;
   1073 	size_t len;
   1074 
   1075 	len = strlen(scheme);
   1076 	if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
   1077 		return 1;
   1078 	uri += len + 3;
   1079 
   1080 	if (userp != NULL)
   1081 		*userp = NULL;
   1082 	if (hostp != NULL)
   1083 		*hostp = NULL;
   1084 	if (portp != NULL)
   1085 		*portp = -1;
   1086 	if (pathp != NULL)
   1087 		*pathp = NULL;
   1088 
   1089 	uridup = tmp = xstrdup(uri);
   1090 
   1091 	/* Extract optional ssh-info (username + connection params) */
   1092 	if ((cp = strchr(tmp, '@')) != NULL) {
   1093 		char *delim;
   1094 
   1095 		*cp = '\0';
   1096 		/* Extract username and connection params */
   1097 		if ((delim = strchr(tmp, ';')) != NULL) {
   1098 			/* Just ignore connection params for now */
   1099 			*delim = '\0';
   1100 		}
   1101 		if (*tmp == '\0') {
   1102 			/* Empty username */
   1103 			goto out;
   1104 		}
   1105 		if ((user = urldecode(tmp)) == NULL)
   1106 			goto out;
   1107 		tmp = cp + 1;
   1108 	}
   1109 
   1110 	/* Extract mandatory hostname */
   1111 	if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
   1112 		goto out;
   1113 	host = xstrdup(cleanhostname(cp));
   1114 	if (!valid_domain(host, 0, NULL))
   1115 		goto out;
   1116 
   1117 	if (tmp != NULL && *tmp != '\0') {
   1118 		if (ch == ':') {
   1119 			/* Convert and verify port. */
   1120 			if ((cp = strchr(tmp, '/')) != NULL)
   1121 				*cp = '\0';
   1122 			if ((port = a2port(tmp)) <= 0)
   1123 				goto out;
   1124 			tmp = cp ? cp + 1 : NULL;
   1125 		}
   1126 		if (tmp != NULL && *tmp != '\0') {
   1127 			/* Extract optional path */
   1128 			if ((path = urldecode(tmp)) == NULL)
   1129 				goto out;
   1130 		}
   1131 	}
   1132 
   1133 	/* Success */
   1134 	if (userp != NULL) {
   1135 		*userp = user;
   1136 		user = NULL;
   1137 	}
   1138 	if (hostp != NULL) {
   1139 		*hostp = host;
   1140 		host = NULL;
   1141 	}
   1142 	if (portp != NULL)
   1143 		*portp = port;
   1144 	if (pathp != NULL) {
   1145 		*pathp = path;
   1146 		path = NULL;
   1147 	}
   1148 	ret = 0;
   1149  out:
   1150 	free(uridup);
   1151 	free(user);
   1152 	free(host);
   1153 	free(path);
   1154 	return ret;
   1155 }
   1156 
   1157 /* function to assist building execv() arguments */
   1158 void
   1159 addargs(arglist *args, const char *fmt, ...)
   1160 {
   1161 	va_list ap;
   1162 	char *cp;
   1163 	u_int nalloc;
   1164 	int r;
   1165 
   1166 	va_start(ap, fmt);
   1167 	r = vasprintf(&cp, fmt, ap);
   1168 	va_end(ap);
   1169 	if (r == -1)
   1170 		fatal_f("argument too long");
   1171 
   1172 	nalloc = args->nalloc;
   1173 	if (args->list == NULL) {
   1174 		nalloc = 32;
   1175 		args->num = 0;
   1176 	} else if (args->num > (256 * 1024))
   1177 		fatal_f("too many arguments");
   1178 	else if (args->num >= args->nalloc)
   1179 		fatal_f("arglist corrupt");
   1180 	else if (args->num+2 >= nalloc)
   1181 		nalloc *= 2;
   1182 
   1183 	args->list = xrecallocarray(args->list, args->nalloc,
   1184 	    nalloc, sizeof(char *));
   1185 	args->nalloc = nalloc;
   1186 	args->list[args->num++] = cp;
   1187 	args->list[args->num] = NULL;
   1188 }
   1189 
   1190 void
   1191 replacearg(arglist *args, u_int which, const char *fmt, ...)
   1192 {
   1193 	va_list ap;
   1194 	char *cp;
   1195 	int r;
   1196 
   1197 	va_start(ap, fmt);
   1198 	r = vasprintf(&cp, fmt, ap);
   1199 	va_end(ap);
   1200 	if (r == -1)
   1201 		fatal_f("argument too long");
   1202 	if (args->list == NULL || args->num >= args->nalloc)
   1203 		fatal_f("arglist corrupt");
   1204 
   1205 	if (which >= args->num)
   1206 		fatal_f("tried to replace invalid arg %d >= %d",
   1207 		    which, args->num);
   1208 	free(args->list[which]);
   1209 	args->list[which] = cp;
   1210 }
   1211 
   1212 void
   1213 freeargs(arglist *args)
   1214 {
   1215 	u_int i;
   1216 
   1217 	if (args == NULL)
   1218 		return;
   1219 	if (args->list != NULL && args->num < args->nalloc) {
   1220 		for (i = 0; i < args->num; i++)
   1221 			free(args->list[i]);
   1222 		free(args->list);
   1223 	}
   1224 	args->nalloc = args->num = 0;
   1225 	args->list = NULL;
   1226 }
   1227 
   1228 /*
   1229  * Expands tildes in the file name.  Returns data allocated by xmalloc.
   1230  * Warning: this calls getpw*.
   1231  */
   1232 int
   1233 tilde_expand(const char *filename, uid_t uid, char **retp)
   1234 {
   1235 	char *ocopy = NULL, *copy, *s = NULL;
   1236 	const char *path = NULL, *user = NULL;
   1237 	struct passwd *pw;
   1238 	size_t len;
   1239 	int ret = -1, r, slash;
   1240 
   1241 	*retp = NULL;
   1242 	if (*filename != '~') {
   1243 		*retp = xstrdup(filename);
   1244 		return 0;
   1245 	}
   1246 	ocopy = copy = xstrdup(filename + 1);
   1247 
   1248 	if (*copy == '\0')				/* ~ */
   1249 		path = NULL;
   1250 	else if (*copy == '/') {
   1251 		copy += strspn(copy, "/");
   1252 		if (*copy == '\0')
   1253 			path = NULL;			/* ~/ */
   1254 		else
   1255 			path = copy;			/* ~/path */
   1256 	} else {
   1257 		user = copy;
   1258 		if ((path = strchr(copy, '/')) != NULL) {
   1259 			copy[path - copy] = '\0';
   1260 			path++;
   1261 			path += strspn(path, "/");
   1262 			if (*path == '\0')		/* ~user/ */
   1263 				path = NULL;
   1264 			/* else				 ~user/path */
   1265 		}
   1266 		/* else					~user */
   1267 	}
   1268 	if (user != NULL) {
   1269 		if ((pw = getpwnam(user)) == NULL) {
   1270 			error_f("No such user %s", user);
   1271 			goto out;
   1272 		}
   1273 	} else if ((pw = getpwuid(uid)) == NULL) {
   1274 		error_f("No such uid %ld", (long)uid);
   1275 		goto out;
   1276 	}
   1277 
   1278 	/* Make sure directory has a trailing '/' */
   1279 	slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
   1280 
   1281 	if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
   1282 	    slash ? "/" : "", path != NULL ? path : "")) <= 0) {
   1283 		error_f("xasprintf failed");
   1284 		goto out;
   1285 	}
   1286 	if (r >= PATH_MAX) {
   1287 		error_f("Path too long");
   1288 		goto out;
   1289 	}
   1290 	/* success */
   1291 	ret = 0;
   1292 	*retp = s;
   1293 	s = NULL;
   1294  out:
   1295 	free(s);
   1296 	free(ocopy);
   1297 	return ret;
   1298 }
   1299 
   1300 char *
   1301 tilde_expand_filename(const char *filename, uid_t uid)
   1302 {
   1303 	char *ret;
   1304 
   1305 	if (tilde_expand(filename, uid, &ret) != 0)
   1306 		cleanup_exit(255);
   1307 	return ret;
   1308 }
   1309 
   1310 /*
   1311  * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
   1312  * substitutions.  A number of escapes may be specified as
   1313  * (char *escape_chars, char *replacement) pairs. The list must be terminated
   1314  * by a NULL escape_char. Returns replaced string in memory allocated by
   1315  * xmalloc which the caller must free.
   1316  */
   1317 static char *
   1318 vdollar_percent_expand(int *parseerror, int dollar, int percent,
   1319     const char *string, va_list ap)
   1320 {
   1321 #define EXPAND_MAX_KEYS	64
   1322 	u_int num_keys = 0, i;
   1323 	struct {
   1324 		const char *key;
   1325 		const char *repl;
   1326 	} keys[EXPAND_MAX_KEYS];
   1327 	struct sshbuf *buf;
   1328 	int r, missingvar = 0;
   1329 	char *ret = NULL, *var, *varend, *val;
   1330 	size_t len;
   1331 
   1332 	if ((buf = sshbuf_new()) == NULL)
   1333 		fatal_f("sshbuf_new failed");
   1334 	if (parseerror == NULL)
   1335 		fatal_f("null parseerror arg");
   1336 	*parseerror = 1;
   1337 
   1338 	/* Gather keys if we're doing percent expansion. */
   1339 	if (percent) {
   1340 		for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
   1341 			keys[num_keys].key = va_arg(ap, char *);
   1342 			if (keys[num_keys].key == NULL)
   1343 				break;
   1344 			keys[num_keys].repl = va_arg(ap, char *);
   1345 			if (keys[num_keys].repl == NULL) {
   1346 				fatal_f("NULL replacement for token %s",
   1347 				    keys[num_keys].key);
   1348 			}
   1349 		}
   1350 		if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
   1351 			fatal_f("too many keys");
   1352 		if (num_keys == 0)
   1353 			fatal_f("percent expansion without token list");
   1354 	}
   1355 
   1356 	/* Expand string */
   1357 	for (i = 0; *string != '\0'; string++) {
   1358 		/* Optionally process ${ENVIRONMENT} expansions. */
   1359 		if (dollar && string[0] == '$' && string[1] == '{') {
   1360 			string += 2;  /* skip over '${' */
   1361 			if ((varend = strchr(string, '}')) == NULL) {
   1362 				error_f("environment variable '%s' missing "
   1363 				    "closing '}'", string);
   1364 				goto out;
   1365 			}
   1366 			len = varend - string;
   1367 			if (len == 0) {
   1368 				error_f("zero-length environment variable");
   1369 				goto out;
   1370 			}
   1371 			var = xmalloc(len + 1);
   1372 			(void)strlcpy(var, string, len + 1);
   1373 			if ((val = getenv(var)) == NULL) {
   1374 				error_f("env var ${%s} has no value", var);
   1375 				missingvar = 1;
   1376 			} else {
   1377 				debug3_f("expand ${%s} -> '%s'", var, val);
   1378 				if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
   1379 					fatal_fr(r, "sshbuf_put ${}");
   1380 			}
   1381 			free(var);
   1382 			string += len;
   1383 			continue;
   1384 		}
   1385 
   1386 		/*
   1387 		 * Process percent expansions if we have a list of TOKENs.
   1388 		 * If we're not doing percent expansion everything just gets
   1389 		 * appended here.
   1390 		 */
   1391 		if (*string != '%' || !percent) {
   1392  append:
   1393 			if ((r = sshbuf_put_u8(buf, *string)) != 0)
   1394 				fatal_fr(r, "sshbuf_put_u8 %%");
   1395 			continue;
   1396 		}
   1397 		string++;
   1398 		/* %% case */
   1399 		if (*string == '%')
   1400 			goto append;
   1401 		if (*string == '\0') {
   1402 			error_f("invalid format");
   1403 			goto out;
   1404 		}
   1405 		for (i = 0; i < num_keys; i++) {
   1406 			if (strchr(keys[i].key, *string) != NULL) {
   1407 				if ((r = sshbuf_put(buf, keys[i].repl,
   1408 				    strlen(keys[i].repl))) != 0)
   1409 					fatal_fr(r, "sshbuf_put %%-repl");
   1410 				break;
   1411 			}
   1412 		}
   1413 		if (i >= num_keys) {
   1414 			error_f("unknown key %%%c", *string);
   1415 			goto out;
   1416 		}
   1417 	}
   1418 	if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
   1419 		fatal_f("sshbuf_dup_string failed");
   1420 	*parseerror = 0;
   1421  out:
   1422 	sshbuf_free(buf);
   1423 	return *parseerror ? NULL : ret;
   1424 #undef EXPAND_MAX_KEYS
   1425 }
   1426 
   1427 /*
   1428  * Expand only environment variables.
   1429  * Note that although this function is variadic like the other similar
   1430  * functions, any such arguments will be unused.
   1431  */
   1432 
   1433 char *
   1434 dollar_expand(int *parseerr, const char *string, ...)
   1435 {
   1436 	char *ret;
   1437 	int err;
   1438 	va_list ap;
   1439 
   1440 	va_start(ap, string);
   1441 	ret = vdollar_percent_expand(&err, 1, 0, string, ap);
   1442 	va_end(ap);
   1443 	if (parseerr != NULL)
   1444 		*parseerr = err;
   1445 	return ret;
   1446 }
   1447 
   1448 /*
   1449  * Returns expanded string or NULL if a specified environment variable is
   1450  * not defined, or calls fatal if the string is invalid.
   1451  */
   1452 char *
   1453 percent_expand(const char *string, ...)
   1454 {
   1455 	char *ret;
   1456 	int err;
   1457 	va_list ap;
   1458 
   1459 	va_start(ap, string);
   1460 	ret = vdollar_percent_expand(&err, 0, 1, string, ap);
   1461 	va_end(ap);
   1462 	if (err)
   1463 		fatal_f("failed");
   1464 	return ret;
   1465 }
   1466 
   1467 /*
   1468  * Returns expanded string or NULL if a specified environment variable is
   1469  * not defined, or calls fatal if the string is invalid.
   1470  */
   1471 char *
   1472 percent_dollar_expand(const char *string, ...)
   1473 {
   1474 	char *ret;
   1475 	int err;
   1476 	va_list ap;
   1477 
   1478 	va_start(ap, string);
   1479 	ret = vdollar_percent_expand(&err, 1, 1, string, ap);
   1480 	va_end(ap);
   1481 	if (err)
   1482 		fatal_f("failed");
   1483 	return ret;
   1484 }
   1485 
   1486 int
   1487 tun_open(int tun, int mode, char **ifname)
   1488 {
   1489 	struct ifreq ifr;
   1490 	char name[100];
   1491 	int fd = -1, sock;
   1492 	const char *tunbase = "tun";
   1493 
   1494 	if (ifname != NULL)
   1495 		*ifname = NULL;
   1496 
   1497 	if (mode == SSH_TUNMODE_ETHERNET)
   1498 		tunbase = "tap";
   1499 
   1500 	/* Open the tunnel device */
   1501 	if (tun <= SSH_TUNID_MAX) {
   1502 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
   1503 		fd = open(name, O_RDWR);
   1504 	} else if (tun == SSH_TUNID_ANY) {
   1505 		for (tun = 100; tun >= 0; tun--) {
   1506 			snprintf(name, sizeof(name), "/dev/%s%d",
   1507 			    tunbase, tun);
   1508 			if ((fd = open(name, O_RDWR)) >= 0)
   1509 				break;
   1510 		}
   1511 	} else {
   1512 		debug_f("invalid tunnel %u", tun);
   1513 		return -1;
   1514 	}
   1515 
   1516 	if (fd == -1) {
   1517 		debug_f("%s open: %s", name, strerror(errno));
   1518 		return -1;
   1519 	}
   1520 
   1521 	debug_f("%s mode %d fd %d", name, mode, fd);
   1522 
   1523 #ifdef TUNSIFHEAD
   1524 	/* Turn on tunnel headers */
   1525 	int flag = 1;
   1526 	if (mode != SSH_TUNMODE_ETHERNET &&
   1527 	    ioctl(fd, TUNSIFHEAD, &flag) == -1) {
   1528 		debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__, fd,
   1529 		    strerror(errno));
   1530 		close(fd);
   1531 		return -1;
   1532 	}
   1533 #endif
   1534 
   1535 	debug("%s: %s mode %d fd %d", __func__, ifr.ifr_name, mode, fd);
   1536 	/* Bring interface up if it is not already */
   1537 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
   1538 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
   1539 		goto failed;
   1540 
   1541 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
   1542 		debug_f("get interface %s flags: %s", ifr.ifr_name,
   1543 		    strerror(errno));
   1544 		goto failed;
   1545 	}
   1546 
   1547 	if (!(ifr.ifr_flags & IFF_UP)) {
   1548 		ifr.ifr_flags |= IFF_UP;
   1549 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
   1550 			debug_f("activate interface %s: %s", ifr.ifr_name,
   1551 			    strerror(errno));
   1552 			goto failed;
   1553 		}
   1554 	}
   1555 
   1556 	if (ifname != NULL)
   1557 		*ifname = xstrdup(ifr.ifr_name);
   1558 
   1559 	close(sock);
   1560 	return fd;
   1561 
   1562  failed:
   1563 	if (fd >= 0)
   1564 		close(fd);
   1565 	if (sock >= 0)
   1566 		close(sock);
   1567 	debug("%s: failed to set %s mode %d: %s", __func__, ifr.ifr_name,
   1568 	    mode, strerror(errno));
   1569 	return -1;
   1570 }
   1571 
   1572 void
   1573 sanitise_stdfd(void)
   1574 {
   1575 	int nullfd, dupfd;
   1576 
   1577 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
   1578 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
   1579 		    strerror(errno));
   1580 		exit(1);
   1581 	}
   1582 	while (++dupfd <= STDERR_FILENO) {
   1583 		/* Only populate closed fds. */
   1584 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
   1585 			if (dup2(nullfd, dupfd) == -1) {
   1586 				fprintf(stderr, "dup2: %s\n", strerror(errno));
   1587 				exit(1);
   1588 			}
   1589 		}
   1590 	}
   1591 	if (nullfd > STDERR_FILENO)
   1592 		close(nullfd);
   1593 }
   1594 
   1595 char *
   1596 tohex(const void *vp, size_t l)
   1597 {
   1598 	const u_char *p = (const u_char *)vp;
   1599 	char b[3], *r;
   1600 	size_t i, hl;
   1601 
   1602 	if (l > 65536)
   1603 		return xstrdup("tohex: length > 65536");
   1604 
   1605 	hl = l * 2 + 1;
   1606 	r = xcalloc(1, hl);
   1607 	for (i = 0; i < l; i++) {
   1608 		snprintf(b, sizeof(b), "%02x", p[i]);
   1609 		strlcat(r, b, hl);
   1610 	}
   1611 	return (r);
   1612 }
   1613 
   1614 /*
   1615  * Extend string *sp by the specified format. If *sp is not NULL (or empty),
   1616  * then the separator 'sep' will be prepended before the formatted arguments.
   1617  * Extended strings are heap allocated.
   1618  */
   1619 void
   1620 xextendf(char **sp, const char *sep, const char *fmt, ...)
   1621 {
   1622 	va_list ap;
   1623 	char *tmp1, *tmp2;
   1624 
   1625 	va_start(ap, fmt);
   1626 	xvasprintf(&tmp1, fmt, ap);
   1627 	va_end(ap);
   1628 
   1629 	if (*sp == NULL || **sp == '\0') {
   1630 		free(*sp);
   1631 		*sp = tmp1;
   1632 		return;
   1633 	}
   1634 	xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
   1635 	free(tmp1);
   1636 	free(*sp);
   1637 	*sp = tmp2;
   1638 }
   1639 
   1640 
   1641 uint64_t
   1642 get_u64(const void *vp)
   1643 {
   1644 	const u_char *p = (const u_char *)vp;
   1645 	uint64_t v;
   1646 
   1647 	v  = (uint64_t)p[0] << 56;
   1648 	v |= (uint64_t)p[1] << 48;
   1649 	v |= (uint64_t)p[2] << 40;
   1650 	v |= (uint64_t)p[3] << 32;
   1651 	v |= (uint64_t)p[4] << 24;
   1652 	v |= (uint64_t)p[5] << 16;
   1653 	v |= (uint64_t)p[6] << 8;
   1654 	v |= (uint64_t)p[7];
   1655 
   1656 	return (v);
   1657 }
   1658 
   1659 uint32_t
   1660 get_u32(const void *vp)
   1661 {
   1662 	const u_char *p = (const u_char *)vp;
   1663 	uint32_t v;
   1664 
   1665 	v  = (uint32_t)p[0] << 24;
   1666 	v |= (uint32_t)p[1] << 16;
   1667 	v |= (uint32_t)p[2] << 8;
   1668 	v |= (uint32_t)p[3];
   1669 
   1670 	return (v);
   1671 }
   1672 
   1673 uint32_t
   1674 get_u32_le(const void *vp)
   1675 {
   1676 	const u_char *p = (const u_char *)vp;
   1677 	uint32_t v;
   1678 
   1679 	v  = (uint32_t)p[0];
   1680 	v |= (uint32_t)p[1] << 8;
   1681 	v |= (uint32_t)p[2] << 16;
   1682 	v |= (uint32_t)p[3] << 24;
   1683 
   1684 	return (v);
   1685 }
   1686 
   1687 uint16_t
   1688 get_u16(const void *vp)
   1689 {
   1690 	const u_char *p = (const u_char *)vp;
   1691 	uint16_t v;
   1692 
   1693 	v  = (uint16_t)p[0] << 8;
   1694 	v |= (uint16_t)p[1];
   1695 
   1696 	return (v);
   1697 }
   1698 
   1699 void
   1700 put_u64(void *vp, uint64_t v)
   1701 {
   1702 	u_char *p = (u_char *)vp;
   1703 
   1704 	p[0] = (u_char)(v >> 56) & 0xff;
   1705 	p[1] = (u_char)(v >> 48) & 0xff;
   1706 	p[2] = (u_char)(v >> 40) & 0xff;
   1707 	p[3] = (u_char)(v >> 32) & 0xff;
   1708 	p[4] = (u_char)(v >> 24) & 0xff;
   1709 	p[5] = (u_char)(v >> 16) & 0xff;
   1710 	p[6] = (u_char)(v >> 8) & 0xff;
   1711 	p[7] = (u_char)v & 0xff;
   1712 }
   1713 
   1714 void
   1715 put_u32(void *vp, uint32_t v)
   1716 {
   1717 	u_char *p = (u_char *)vp;
   1718 
   1719 	p[0] = (u_char)(v >> 24) & 0xff;
   1720 	p[1] = (u_char)(v >> 16) & 0xff;
   1721 	p[2] = (u_char)(v >> 8) & 0xff;
   1722 	p[3] = (u_char)v & 0xff;
   1723 }
   1724 
   1725 void
   1726 put_u32_le(void *vp, uint32_t v)
   1727 {
   1728 	u_char *p = (u_char *)vp;
   1729 
   1730 	p[0] = (u_char)v & 0xff;
   1731 	p[1] = (u_char)(v >> 8) & 0xff;
   1732 	p[2] = (u_char)(v >> 16) & 0xff;
   1733 	p[3] = (u_char)(v >> 24) & 0xff;
   1734 }
   1735 
   1736 void
   1737 put_u16(void *vp, uint16_t v)
   1738 {
   1739 	u_char *p = (u_char *)vp;
   1740 
   1741 	p[0] = (u_char)(v >> 8) & 0xff;
   1742 	p[1] = (u_char)v & 0xff;
   1743 }
   1744 
   1745 void
   1746 ms_subtract_diff(struct timeval *start, int *ms)
   1747 {
   1748 	struct timeval diff, finish;
   1749 
   1750 	monotime_tv(&finish);
   1751 	timersub(&finish, start, &diff);
   1752 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
   1753 }
   1754 
   1755 void
   1756 ms_to_timespec(struct timespec *ts, int ms)
   1757 {
   1758 	if (ms < 0)
   1759 		ms = 0;
   1760 	ts->tv_sec = ms / 1000;
   1761 	ts->tv_nsec = (ms % 1000) * 1000 * 1000;
   1762 }
   1763 
   1764 void
   1765 monotime_ts(struct timespec *ts)
   1766 {
   1767 	if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
   1768 		fatal("clock_gettime: %s", strerror(errno));
   1769 }
   1770 
   1771 void
   1772 monotime_tv(struct timeval *tv)
   1773 {
   1774 	struct timespec ts;
   1775 
   1776 	monotime_ts(&ts);
   1777 	tv->tv_sec = ts.tv_sec;
   1778 	tv->tv_usec = ts.tv_nsec / 1000;
   1779 }
   1780 
   1781 time_t
   1782 monotime(void)
   1783 {
   1784 	struct timespec ts;
   1785 
   1786 	monotime_ts(&ts);
   1787 	return (ts.tv_sec);
   1788 }
   1789 
   1790 double
   1791 monotime_double(void)
   1792 {
   1793 	struct timespec ts;
   1794 
   1795 	monotime_ts(&ts);
   1796 	return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
   1797 }
   1798 
   1799 void
   1800 bandwidth_limit_init(struct bwlimit *bw, uint64_t kbps, size_t buflen)
   1801 {
   1802 	bw->buflen = buflen;
   1803 	bw->rate = kbps;
   1804 	bw->thresh = buflen;
   1805 	bw->lamt = 0;
   1806 	timerclear(&bw->bwstart);
   1807 	timerclear(&bw->bwend);
   1808 }
   1809 
   1810 /* Callback from read/write loop to insert bandwidth-limiting delays */
   1811 void
   1812 bandwidth_limit(struct bwlimit *bw, size_t read_len)
   1813 {
   1814 	uint64_t waitlen;
   1815 	struct timespec ts, rm;
   1816 
   1817 	bw->lamt += read_len;
   1818 	if (!timerisset(&bw->bwstart)) {
   1819 		monotime_tv(&bw->bwstart);
   1820 		return;
   1821 	}
   1822 	if (bw->lamt < bw->thresh)
   1823 		return;
   1824 
   1825 	monotime_tv(&bw->bwend);
   1826 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
   1827 	if (!timerisset(&bw->bwend))
   1828 		return;
   1829 
   1830 	bw->lamt *= 8;
   1831 	waitlen = (double)1000000L * bw->lamt / bw->rate;
   1832 
   1833 	bw->bwstart.tv_sec = waitlen / 1000000L;
   1834 	bw->bwstart.tv_usec = waitlen % 1000000L;
   1835 
   1836 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
   1837 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
   1838 
   1839 		/* Adjust the wait time */
   1840 		if (bw->bwend.tv_sec) {
   1841 			bw->thresh /= 2;
   1842 			if (bw->thresh < bw->buflen / 4)
   1843 				bw->thresh = bw->buflen / 4;
   1844 		} else if (bw->bwend.tv_usec < 10000) {
   1845 			bw->thresh *= 2;
   1846 			if (bw->thresh > bw->buflen * 8)
   1847 				bw->thresh = bw->buflen * 8;
   1848 		}
   1849 
   1850 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
   1851 		while (nanosleep(&ts, &rm) == -1) {
   1852 			if (errno != EINTR)
   1853 				break;
   1854 			ts = rm;
   1855 		}
   1856 	}
   1857 
   1858 	bw->lamt = 0;
   1859 	monotime_tv(&bw->bwstart);
   1860 }
   1861 
   1862 /* Make a template filename for mk[sd]temp() */
   1863 void
   1864 mktemp_proto(char *s, size_t len)
   1865 {
   1866 	const char *tmpdir;
   1867 	int r;
   1868 
   1869 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
   1870 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
   1871 		if (r > 0 && (size_t)r < len)
   1872 			return;
   1873 	}
   1874 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
   1875 	if (r < 0 || (size_t)r >= len)
   1876 		fatal_f("template string too short");
   1877 }
   1878 
   1879 static const struct {
   1880 	const char *name;
   1881 	int value;
   1882 } ipqos[] = {
   1883 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
   1884 	{ "af11", IPTOS_DSCP_AF11 },
   1885 	{ "af12", IPTOS_DSCP_AF12 },
   1886 	{ "af13", IPTOS_DSCP_AF13 },
   1887 	{ "af21", IPTOS_DSCP_AF21 },
   1888 	{ "af22", IPTOS_DSCP_AF22 },
   1889 	{ "af23", IPTOS_DSCP_AF23 },
   1890 	{ "af31", IPTOS_DSCP_AF31 },
   1891 	{ "af32", IPTOS_DSCP_AF32 },
   1892 	{ "af33", IPTOS_DSCP_AF33 },
   1893 	{ "af41", IPTOS_DSCP_AF41 },
   1894 	{ "af42", IPTOS_DSCP_AF42 },
   1895 	{ "af43", IPTOS_DSCP_AF43 },
   1896 	{ "cs0", IPTOS_DSCP_CS0 },
   1897 	{ "cs1", IPTOS_DSCP_CS1 },
   1898 	{ "cs2", IPTOS_DSCP_CS2 },
   1899 	{ "cs3", IPTOS_DSCP_CS3 },
   1900 	{ "cs4", IPTOS_DSCP_CS4 },
   1901 	{ "cs5", IPTOS_DSCP_CS5 },
   1902 	{ "cs6", IPTOS_DSCP_CS6 },
   1903 	{ "cs7", IPTOS_DSCP_CS7 },
   1904 	{ "ef", IPTOS_DSCP_EF },
   1905 #ifdef IPTOS_DSCP_LE
   1906 	{ "le", IPTOS_DSCP_LE },
   1907 #endif
   1908 #ifdef IPTOS_DSCP_VA
   1909 	{ "va",	IPTOS_DSCP_VA },
   1910 #endif
   1911 	{ "lowdelay", INT_MIN },	/* deprecated */
   1912 	{ "throughput", INT_MIN },	/* deprecated */
   1913 	{ "reliability", INT_MIN },	/* deprecated */
   1914 	{ NULL, -1 }
   1915 };
   1916 
   1917 int
   1918 parse_ipqos(const char *cp)
   1919 {
   1920 	const char *errstr;
   1921 	u_int i;
   1922 	int val;
   1923 
   1924 	if (cp == NULL)
   1925 		return -1;
   1926 	for (i = 0; ipqos[i].name != NULL; i++) {
   1927 		if (strcasecmp(cp, ipqos[i].name) == 0)
   1928 			return ipqos[i].value;
   1929 	}
   1930 	/* Try parsing as an integer */
   1931 	val = (int)strtonum(cp, 0, 255, &errstr);
   1932 	if (errstr)
   1933 		return -1;
   1934 	return val;
   1935 }
   1936 
   1937 const char *
   1938 iptos2str(int iptos)
   1939 {
   1940 	int i;
   1941 	static char iptos_str[sizeof "0xff"];
   1942 
   1943 	for (i = 0; ipqos[i].name != NULL; i++) {
   1944 		if (ipqos[i].value == iptos)
   1945 			return ipqos[i].name;
   1946 	}
   1947 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
   1948 	return iptos_str;
   1949 }
   1950 
   1951 void
   1952 lowercase(char *s)
   1953 {
   1954 	for (; *s; s++)
   1955 		*s = tolower((u_char)*s);
   1956 }
   1957 
   1958 int
   1959 unix_listener(const char *path, int backlog, int unlink_first)
   1960 {
   1961 	struct sockaddr_un sunaddr;
   1962 	int saved_errno, sock;
   1963 
   1964 	memset(&sunaddr, 0, sizeof(sunaddr));
   1965 	sunaddr.sun_family = AF_UNIX;
   1966 	if (strlcpy(sunaddr.sun_path, path,
   1967 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
   1968 		error_f("path \"%s\" too long for Unix domain socket", path);
   1969 		errno = ENAMETOOLONG;
   1970 		return -1;
   1971 	}
   1972 
   1973 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
   1974 	if (sock == -1) {
   1975 		saved_errno = errno;
   1976 		error_f("socket: %.100s", strerror(errno));
   1977 		errno = saved_errno;
   1978 		return -1;
   1979 	}
   1980 	if (unlink_first == 1) {
   1981 		if (unlink(path) != 0 && errno != ENOENT)
   1982 			error("unlink(%s): %.100s", path, strerror(errno));
   1983 	}
   1984 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
   1985 		saved_errno = errno;
   1986 		error_f("cannot bind to path %s: %s", path, strerror(errno));
   1987 		close(sock);
   1988 		errno = saved_errno;
   1989 		return -1;
   1990 	}
   1991 	if (listen(sock, backlog) == -1) {
   1992 		saved_errno = errno;
   1993 		error_f("cannot listen on path %s: %s", path, strerror(errno));
   1994 		close(sock);
   1995 		unlink(path);
   1996 		errno = saved_errno;
   1997 		return -1;
   1998 	}
   1999 	return sock;
   2000 }
   2001 
   2002 /*
   2003  * Compares two strings that maybe be NULL. Returns non-zero if strings
   2004  * are both NULL or are identical, returns zero otherwise.
   2005  */
   2006 static int
   2007 strcmp_maybe_null(const char *a, const char *b)
   2008 {
   2009 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
   2010 		return 0;
   2011 	if (a != NULL && strcmp(a, b) != 0)
   2012 		return 0;
   2013 	return 1;
   2014 }
   2015 
   2016 /*
   2017  * Compare two forwards, returning non-zero if they are identical or
   2018  * zero otherwise.
   2019  */
   2020 int
   2021 forward_equals(const struct Forward *a, const struct Forward *b)
   2022 {
   2023 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
   2024 		return 0;
   2025 	if (a->listen_port != b->listen_port)
   2026 		return 0;
   2027 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
   2028 		return 0;
   2029 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
   2030 		return 0;
   2031 	if (a->connect_port != b->connect_port)
   2032 		return 0;
   2033 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
   2034 		return 0;
   2035 	/* allocated_port and handle are not checked */
   2036 	return 1;
   2037 }
   2038 
   2039 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
   2040 int
   2041 permitopen_port(const char *p)
   2042 {
   2043 	int port;
   2044 
   2045 	if (strcmp(p, "*") == 0)
   2046 		return FWD_PERMIT_ANY_PORT;
   2047 	if ((port = a2port(p)) > 0)
   2048 		return port;
   2049 	return -1;
   2050 }
   2051 
   2052 /* returns 1 if process is already daemonized, 0 otherwise */
   2053 int
   2054 daemonized(void)
   2055 {
   2056 	int fd;
   2057 
   2058 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
   2059 		close(fd);
   2060 		return 0;	/* have controlling terminal */
   2061 	}
   2062 	if (getppid() != 1)
   2063 		return 0;	/* parent is not init */
   2064 	if (getsid(0) != getpid())
   2065 		return 0;	/* not session leader */
   2066 	debug3("already daemonized");
   2067 	return 1;
   2068 }
   2069 
   2070 /*
   2071  * Splits 's' into an argument vector. Handles quoted string and basic
   2072  * escape characters (\\, \", \'). Caller must free the argument vector
   2073  * and its members.
   2074  */
   2075 int
   2076 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
   2077 {
   2078 	int r = SSH_ERR_INTERNAL_ERROR;
   2079 	int argc = 0, quote, i, j;
   2080 	char *arg, **argv = xcalloc(1, sizeof(*argv));
   2081 
   2082 	*argvp = NULL;
   2083 	*argcp = 0;
   2084 
   2085 	for (i = 0; s[i] != '\0'; i++) {
   2086 		/* Skip leading whitespace */
   2087 		if (s[i] == ' ' || s[i] == '\t')
   2088 			continue;
   2089 		if (terminate_on_comment && s[i] == '#')
   2090 			break;
   2091 		/* Start of a token */
   2092 		quote = 0;
   2093 
   2094 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
   2095 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
   2096 		argv[argc] = NULL;
   2097 
   2098 		/* Copy the token in, removing escapes */
   2099 		for (j = 0; s[i] != '\0'; i++) {
   2100 			if (s[i] == '\\') {
   2101 				if (s[i + 1] == '\'' ||
   2102 				    s[i + 1] == '\"' ||
   2103 				    s[i + 1] == '\\' ||
   2104 				    (quote == 0 && s[i + 1] == ' ')) {
   2105 					i++; /* Skip '\' */
   2106 					arg[j++] = s[i];
   2107 				} else {
   2108 					/* Unrecognised escape */
   2109 					arg[j++] = s[i];
   2110 				}
   2111 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
   2112 				break; /* done */
   2113 			else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
   2114 				quote = s[i]; /* quote start */
   2115 			else if (quote != 0 && s[i] == quote)
   2116 				quote = 0; /* quote end */
   2117 			else
   2118 				arg[j++] = s[i];
   2119 		}
   2120 		if (s[i] == '\0') {
   2121 			if (quote != 0) {
   2122 				/* Ran out of string looking for close quote */
   2123 				r = SSH_ERR_INVALID_FORMAT;
   2124 				goto out;
   2125 			}
   2126 			break;
   2127 		}
   2128 	}
   2129 	/* Success */
   2130 	*argcp = argc;
   2131 	*argvp = argv;
   2132 	argc = 0;
   2133 	argv = NULL;
   2134 	r = 0;
   2135  out:
   2136 	if (argc != 0 && argv != NULL) {
   2137 		for (i = 0; i < argc; i++)
   2138 			free(argv[i]);
   2139 		free(argv);
   2140 	}
   2141 	return r;
   2142 }
   2143 
   2144 /*
   2145  * Reassemble an argument vector into a string, quoting and escaping as
   2146  * necessary. Caller must free returned string.
   2147  */
   2148 char *
   2149 argv_assemble(int argc, char **argv)
   2150 {
   2151 	int i, j, ws, r;
   2152 	char c, *ret;
   2153 	struct sshbuf *buf, *arg;
   2154 
   2155 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
   2156 		fatal_f("sshbuf_new failed");
   2157 
   2158 	for (i = 0; i < argc; i++) {
   2159 		ws = 0;
   2160 		sshbuf_reset(arg);
   2161 		for (j = 0; argv[i][j] != '\0'; j++) {
   2162 			r = 0;
   2163 			c = argv[i][j];
   2164 			switch (c) {
   2165 			case ' ':
   2166 			case '\t':
   2167 				ws = 1;
   2168 				r = sshbuf_put_u8(arg, c);
   2169 				break;
   2170 			case '\\':
   2171 			case '\'':
   2172 			case '"':
   2173 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
   2174 					break;
   2175 				/* FALLTHROUGH */
   2176 			default:
   2177 				r = sshbuf_put_u8(arg, c);
   2178 				break;
   2179 			}
   2180 			if (r != 0)
   2181 				fatal_fr(r, "sshbuf_put_u8");
   2182 		}
   2183 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
   2184 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
   2185 		    (r = sshbuf_putb(buf, arg)) != 0 ||
   2186 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
   2187 			fatal_fr(r, "assemble");
   2188 	}
   2189 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
   2190 		fatal_f("malloc failed");
   2191 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
   2192 	ret[sshbuf_len(buf)] = '\0';
   2193 	sshbuf_free(buf);
   2194 	sshbuf_free(arg);
   2195 	return ret;
   2196 }
   2197 
   2198 char *
   2199 argv_next(int *argcp, char ***argvp)
   2200 {
   2201 	char *ret = (*argvp)[0];
   2202 
   2203 	if (*argcp > 0 && ret != NULL) {
   2204 		(*argcp)--;
   2205 		(*argvp)++;
   2206 	}
   2207 	return ret;
   2208 }
   2209 
   2210 void
   2211 argv_consume(int *argcp)
   2212 {
   2213 	*argcp = 0;
   2214 }
   2215 
   2216 void
   2217 argv_free(char **av, int ac)
   2218 {
   2219 	int i;
   2220 
   2221 	if (av == NULL)
   2222 		return;
   2223 	for (i = 0; i < ac; i++)
   2224 		free(av[i]);
   2225 	free(av);
   2226 }
   2227 
   2228 /* Returns 0 if pid exited cleanly, non-zero otherwise */
   2229 int
   2230 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
   2231 {
   2232 	int status;
   2233 
   2234 	while (waitpid(pid, &status, 0) == -1) {
   2235 		if (errno != EINTR) {
   2236 			error("%s waitpid: %s", tag, strerror(errno));
   2237 			return -1;
   2238 		}
   2239 	}
   2240 	if (WIFSIGNALED(status)) {
   2241 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
   2242 		return -1;
   2243 	} else if (WEXITSTATUS(status) != 0) {
   2244 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
   2245 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
   2246 		return -1;
   2247 	}
   2248 	return 0;
   2249 }
   2250 
   2251 /*
   2252  * Check a given path for security. This is defined as all components
   2253  * of the path to the file must be owned by either the owner of
   2254  * of the file or root and no directories must be group or world writable.
   2255  *
   2256  * XXX Should any specific check be done for sym links ?
   2257  *
   2258  * Takes a file name, its stat information (preferably from fstat() to
   2259  * avoid races), the uid of the expected owner, their home directory and an
   2260  * error buffer plus max size as arguments.
   2261  *
   2262  * Returns 0 on success and -1 on failure
   2263  */
   2264 int
   2265 safe_path(const char *name, struct stat *stp, const char *pw_dir,
   2266     uid_t uid, char *err, size_t errlen)
   2267 {
   2268 	char buf[PATH_MAX], buf2[PATH_MAX], homedir[PATH_MAX];
   2269 	char *cp;
   2270 	int comparehome = 0;
   2271 	struct stat st;
   2272 
   2273 	if (realpath(name, buf) == NULL) {
   2274 		snprintf(err, errlen, "realpath %s failed: %s", name,
   2275 		    strerror(errno));
   2276 		return -1;
   2277 	}
   2278 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
   2279 		comparehome = 1;
   2280 
   2281 	if (!S_ISREG(stp->st_mode)) {
   2282 		snprintf(err, errlen, "%s is not a regular file", buf);
   2283 		return -1;
   2284 	}
   2285 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
   2286 	    (stp->st_mode & 022) != 0) {
   2287 		snprintf(err, errlen, "bad ownership or modes for file %s",
   2288 		    buf);
   2289 		return -1;
   2290 	}
   2291 
   2292 	/* for each component of the canonical path, walking upwards */
   2293 	for (;;) {
   2294 		/*
   2295 		 * POSIX allows dirname to modify its argument and return a
   2296 		 * pointer into it, so make a copy to avoid overlapping strlcpy.
   2297 		 */
   2298 		strlcpy(buf2, buf, sizeof(buf2));
   2299 		if ((cp = dirname(buf2)) == NULL) {
   2300 			snprintf(err, errlen, "dirname() failed");
   2301 			return -1;
   2302 		}
   2303 		strlcpy(buf, cp, sizeof(buf));
   2304 
   2305 		if (stat(buf, &st) == -1 ||
   2306 		    (st.st_uid != 0 && st.st_uid != uid) ||
   2307 		    (st.st_mode & 022) != 0) {
   2308 			snprintf(err, errlen,
   2309 			    "bad ownership or modes for directory %s", buf);
   2310 			return -1;
   2311 		}
   2312 
   2313 		/* If are past the homedir then we can stop */
   2314 		if (comparehome && strcmp(homedir, buf) == 0)
   2315 			break;
   2316 
   2317 		/*
   2318 		 * dirname should always complete with a "/" path,
   2319 		 * but we can be paranoid and check for "." too
   2320 		 */
   2321 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
   2322 			break;
   2323 	}
   2324 	return 0;
   2325 }
   2326 
   2327 /*
   2328  * Version of safe_path() that accepts an open file descriptor to
   2329  * avoid races.
   2330  *
   2331  * Returns 0 on success and -1 on failure
   2332  */
   2333 int
   2334 safe_path_fd(int fd, const char *file, struct passwd *pw,
   2335     char *err, size_t errlen)
   2336 {
   2337 	struct stat st;
   2338 
   2339 	/* check the open file to avoid races */
   2340 	if (fstat(fd, &st) == -1) {
   2341 		snprintf(err, errlen, "cannot stat file %s: %s",
   2342 		    file, strerror(errno));
   2343 		return -1;
   2344 	}
   2345 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
   2346 }
   2347 
   2348 /*
   2349  * Sets the value of the given variable in the environment.  If the variable
   2350  * already exists, its value is overridden.
   2351  */
   2352 void
   2353 child_set_env(char ***envp, u_int *envsizep, const char *name,
   2354 	const char *value)
   2355 {
   2356 	char **env;
   2357 	u_int envsize;
   2358 	u_int i, namelen;
   2359 
   2360 	if (strchr(name, '=') != NULL) {
   2361 		error("Invalid environment variable \"%.100s\"", name);
   2362 		return;
   2363 	}
   2364 
   2365 	/*
   2366 	 * Find the slot where the value should be stored.  If the variable
   2367 	 * already exists, we reuse the slot; otherwise we append a new slot
   2368 	 * at the end of the array, expanding if necessary.
   2369 	 */
   2370 	env = *envp;
   2371 	namelen = strlen(name);
   2372 	for (i = 0; env[i]; i++)
   2373 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
   2374 			break;
   2375 	if (env[i]) {
   2376 		/* Reuse the slot. */
   2377 		free(env[i]);
   2378 	} else {
   2379 		/* New variable.  Expand if necessary. */
   2380 		envsize = *envsizep;
   2381 		if (i >= envsize - 1) {
   2382 			if (envsize >= 1000)
   2383 				fatal("child_set_env: too many env vars");
   2384 			envsize += 50;
   2385 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
   2386 			*envsizep = envsize;
   2387 		}
   2388 		/* Need to set the NULL pointer at end of array beyond the new slot. */
   2389 		env[i + 1] = NULL;
   2390 	}
   2391 
   2392 	/* Allocate space and format the variable in the appropriate slot. */
   2393 	/* XXX xasprintf */
   2394 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
   2395 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
   2396 }
   2397 
   2398 /*
   2399  * Check and optionally lowercase a domain name, also removes trailing '.'
   2400  * Returns 1 on success and 0 on failure, storing an error message in errstr.
   2401  */
   2402 int
   2403 valid_domain(char *name, int makelower, const char **errstr)
   2404 {
   2405 	size_t i, l = strlen(name);
   2406 	u_char c, last = '\0';
   2407 	static char errbuf[256];
   2408 
   2409 	if (l == 0) {
   2410 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
   2411 		goto bad;
   2412 	}
   2413 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0]) &&
   2414 	   name[0] != '_' /* technically invalid, but common */) {
   2415 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
   2416 		    "starts with invalid character", name);
   2417 		goto bad;
   2418 	}
   2419 	for (i = 0; i < l; i++) {
   2420 		c = tolower((u_char)name[i]);
   2421 		if (makelower)
   2422 			name[i] = (char)c;
   2423 		if (last == '.' && c == '.') {
   2424 			snprintf(errbuf, sizeof(errbuf), "domain name "
   2425 			    "\"%.100s\" contains consecutive separators", name);
   2426 			goto bad;
   2427 		}
   2428 		if (c != '.' && c != '-' && !isalnum(c) &&
   2429 		    c != '_') /* technically invalid, but common */ {
   2430 			snprintf(errbuf, sizeof(errbuf), "domain name "
   2431 			    "\"%.100s\" contains invalid characters", name);
   2432 			goto bad;
   2433 		}
   2434 		last = c;
   2435 	}
   2436 	if (name[l - 1] == '.')
   2437 		name[l - 1] = '\0';
   2438 	if (errstr != NULL)
   2439 		*errstr = NULL;
   2440 	return 1;
   2441 bad:
   2442 	if (errstr != NULL)
   2443 		*errstr = errbuf;
   2444 	return 0;
   2445 }
   2446 
   2447 /*
   2448  * Verify that a environment variable name (not including initial '$') is
   2449  * valid; consisting of one or more alphanumeric or underscore characters only.
   2450  * Returns 1 on valid, 0 otherwise.
   2451  */
   2452 int
   2453 valid_env_name(const char *name)
   2454 {
   2455 	const char *cp;
   2456 
   2457 	if (name[0] == '\0')
   2458 		return 0;
   2459 	for (cp = name; *cp != '\0'; cp++) {
   2460 		if (!isalnum((u_char)*cp) && *cp != '_')
   2461 			return 0;
   2462 	}
   2463 	return 1;
   2464 }
   2465 
   2466 const char *
   2467 atoi_err(const char *nptr, int *val)
   2468 {
   2469 	const char *errstr = NULL;
   2470 
   2471 	if (nptr == NULL || *nptr == '\0')
   2472 		return "missing";
   2473 	*val = strtonum(nptr, 0, INT_MAX, &errstr);
   2474 	return errstr;
   2475 }
   2476 
   2477 int
   2478 parse_absolute_time(const char *s, uint64_t *tp)
   2479 {
   2480 	struct tm tm;
   2481 	time_t tt;
   2482 	char buf[32];
   2483 	const char *fmt, *cp;
   2484 	size_t l;
   2485 	int is_utc = 0;
   2486 
   2487 	*tp = 0;
   2488 
   2489 	l = strlen(s);
   2490 	if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
   2491 		is_utc = 1;
   2492 		l--;
   2493 	} else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
   2494 		is_utc = 1;
   2495 		l -= 3;
   2496 	}
   2497 	/*
   2498 	 * POSIX strptime says "The application shall ensure that there
   2499 	 * is white-space or other non-alphanumeric characters between
   2500 	 * any two conversion specifications" so arrange things this way.
   2501 	 */
   2502 	switch (l) {
   2503 	case 8: /* YYYYMMDD */
   2504 		fmt = "%Y-%m-%d";
   2505 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
   2506 		break;
   2507 	case 12: /* YYYYMMDDHHMM */
   2508 		fmt = "%Y-%m-%dT%H:%M";
   2509 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
   2510 		    s, s + 4, s + 6, s + 8, s + 10);
   2511 		break;
   2512 	case 14: /* YYYYMMDDHHMMSS */
   2513 		fmt = "%Y-%m-%dT%H:%M:%S";
   2514 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
   2515 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
   2516 		break;
   2517 	default:
   2518 		return SSH_ERR_INVALID_FORMAT;
   2519 	}
   2520 
   2521 	memset(&tm, 0, sizeof(tm));
   2522 	if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
   2523 		return SSH_ERR_INVALID_FORMAT;
   2524 	if (is_utc) {
   2525 		if ((tt = timegm(&tm)) < 0)
   2526 			return SSH_ERR_INVALID_FORMAT;
   2527 	} else {
   2528 		if ((tt = mktime(&tm)) < 0)
   2529 			return SSH_ERR_INVALID_FORMAT;
   2530 	}
   2531 	/* success */
   2532 	*tp = (uint64_t)tt;
   2533 	return 0;
   2534 }
   2535 
   2536 void
   2537 format_absolute_time(uint64_t t, char *buf, size_t len)
   2538 {
   2539 	time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
   2540 	struct tm tm;
   2541 
   2542 	if (localtime_r(&tt, &tm) == NULL)
   2543 		strlcpy(buf, "UNKNOWN-TIME", len);
   2544 	else
   2545 		strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
   2546 }
   2547 
   2548 /*
   2549  * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
   2550  * Returns 0 on success or non-zero on failure.
   2551  * Caller must free *typep.
   2552  */
   2553 int
   2554 parse_pattern_interval(const char *s, char **typep, int *secsp)
   2555 {
   2556 	char *cp, *sdup;
   2557 	int secs;
   2558 
   2559 	if (typep != NULL)
   2560 		*typep = NULL;
   2561 	if (secsp != NULL)
   2562 		*secsp = 0;
   2563 	if (s == NULL)
   2564 		return -1;
   2565 	sdup = xstrdup(s);
   2566 
   2567 	if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
   2568 		free(sdup);
   2569 		return -1;
   2570 	}
   2571 	*cp++ = '\0';
   2572 	if ((secs = convtime(cp)) < 0) {
   2573 		free(sdup);
   2574 		return -1;
   2575 	}
   2576 	/* success */
   2577 	if (typep != NULL)
   2578 		*typep = xstrdup(sdup);
   2579 	if (secsp != NULL)
   2580 		*secsp = secs;
   2581 	free(sdup);
   2582 	return 0;
   2583 }
   2584 
   2585 /* check if path is absolute */
   2586 int
   2587 path_absolute(const char *path)
   2588 {
   2589 	return (*path == '/') ? 1 : 0;
   2590 }
   2591 
   2592 void
   2593 skip_space(char **cpp)
   2594 {
   2595 	char *cp;
   2596 
   2597 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
   2598 		;
   2599 	*cpp = cp;
   2600 }
   2601 
   2602 /* authorized_key-style options parsing helpers */
   2603 
   2604 /*
   2605  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
   2606  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
   2607  * if negated option matches.
   2608  * If the option or negated option matches, then *optsp is updated to
   2609  * point to the first character after the option.
   2610  */
   2611 int
   2612 opt_flag(const char *opt, int allow_negate, const char **optsp)
   2613 {
   2614 	size_t opt_len = strlen(opt);
   2615 	const char *opts = *optsp;
   2616 	int negate = 0;
   2617 
   2618 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
   2619 		opts += 3;
   2620 		negate = 1;
   2621 	}
   2622 	if (strncasecmp(opts, opt, opt_len) == 0) {
   2623 		*optsp = opts + opt_len;
   2624 		return negate ? 0 : 1;
   2625 	}
   2626 	return -1;
   2627 }
   2628 
   2629 char *
   2630 opt_dequote(const char **sp, const char **errstrp)
   2631 {
   2632 	const char *s = *sp;
   2633 	char *ret;
   2634 	size_t i;
   2635 
   2636 	*errstrp = NULL;
   2637 	if (*s != '"') {
   2638 		*errstrp = "missing start quote";
   2639 		return NULL;
   2640 	}
   2641 	s++;
   2642 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
   2643 		*errstrp = "memory allocation failed";
   2644 		return NULL;
   2645 	}
   2646 	for (i = 0; *s != '\0' && *s != '"';) {
   2647 		if (s[0] == '\\' && s[1] == '"')
   2648 			s++;
   2649 		ret[i++] = *s++;
   2650 	}
   2651 	if (*s == '\0') {
   2652 		*errstrp = "missing end quote";
   2653 		free(ret);
   2654 		return NULL;
   2655 	}
   2656 	ret[i] = '\0';
   2657 	s++;
   2658 	*sp = s;
   2659 	return ret;
   2660 }
   2661 
   2662 int
   2663 opt_match(const char **opts, const char *term)
   2664 {
   2665 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
   2666 	    (*opts)[strlen(term)] == '=') {
   2667 		*opts += strlen(term) + 1;
   2668 		return 1;
   2669 	}
   2670 	return 0;
   2671 }
   2672 
   2673 void
   2674 opt_array_append2(const char *file, const int line, const char *directive,
   2675     char ***array, int **iarray, u_int *lp, const char *s, int i)
   2676 {
   2677 
   2678 	if (*lp >= INT_MAX)
   2679 		fatal("%s line %d: Too many %s entries", file, line, directive);
   2680 
   2681 	if (iarray != NULL) {
   2682 		*iarray = xrecallocarray(*iarray, *lp, *lp + 1,
   2683 		    sizeof(**iarray));
   2684 		(*iarray)[*lp] = i;
   2685 	}
   2686 
   2687 	*array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
   2688 	(*array)[*lp] = xstrdup(s);
   2689 	(*lp)++;
   2690 }
   2691 
   2692 void
   2693 opt_array_append(const char *file, const int line, const char *directive,
   2694     char ***array, u_int *lp, const char *s)
   2695 {
   2696 	opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
   2697 }
   2698 
   2699 void
   2700 opt_array_free2(char **array, int **iarray, u_int l)
   2701 {
   2702 	u_int i;
   2703 
   2704 	if (array == NULL || l == 0)
   2705 		return;
   2706 	for (i = 0; i < l; i++)
   2707 		free(array[i]);
   2708 	free(array);
   2709 	free(iarray);
   2710 }
   2711 
   2712 sshsig_t
   2713 ssh_signal(int signum, sshsig_t handler)
   2714 {
   2715 	struct sigaction sa, osa;
   2716 
   2717 	/* mask all other signals while in handler */
   2718 	memset(&sa, 0, sizeof(sa));
   2719 	sa.sa_handler = handler;
   2720 	sigfillset(&sa.sa_mask);
   2721 	if (signum != SIGALRM)
   2722 		sa.sa_flags = SA_RESTART;
   2723 	if (sigaction(signum, &sa, &osa) == -1) {
   2724 		debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
   2725 		return SIG_ERR;
   2726 	}
   2727 	return osa.sa_handler;
   2728 }
   2729 
   2730 int
   2731 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
   2732 {
   2733 	int devnull, ret = 0;
   2734 
   2735 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
   2736 		error_f("open %s: %s", _PATH_DEVNULL,
   2737 		    strerror(errno));
   2738 		return -1;
   2739 	}
   2740 	if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
   2741 	    (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
   2742 	    (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
   2743 		error_f("dup2: %s", strerror(errno));
   2744 		ret = -1;
   2745 	}
   2746 	if (devnull > STDERR_FILENO)
   2747 		close(devnull);
   2748 	return ret;
   2749 }
   2750 
   2751 /*
   2752  * Runs command in a subprocess with a minimal environment.
   2753  * Returns pid on success, 0 on failure.
   2754  * The child stdout and stderr maybe captured, left attached or sent to
   2755  * /dev/null depending on the contents of flags.
   2756  * "tag" is prepended to log messages.
   2757  * NB. "command" is only used for logging; the actual command executed is
   2758  * av[0].
   2759  */
   2760 pid_t
   2761 subprocess(const char *tag, const char *command,
   2762     int ac, char **av, FILE **child, u_int flags,
   2763     struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
   2764 {
   2765 	FILE *f = NULL;
   2766 	struct stat st;
   2767 	int fd, devnull, p[2], i;
   2768 	pid_t pid;
   2769 	char *cp, errmsg[512];
   2770 	u_int nenv = 0;
   2771 	char **env = NULL;
   2772 
   2773 	/* If dropping privs, then must specify user and restore function */
   2774 	if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
   2775 		error("%s: inconsistent arguments", tag); /* XXX fatal? */
   2776 		return 0;
   2777 	}
   2778 	if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
   2779 		error("%s: no user for current uid", tag);
   2780 		return 0;
   2781 	}
   2782 	if (child != NULL)
   2783 		*child = NULL;
   2784 
   2785 	debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
   2786 	    tag, command, pw->pw_name, flags);
   2787 
   2788 	/* Check consistency */
   2789 	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
   2790 	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
   2791 		error_f("inconsistent flags");
   2792 		return 0;
   2793 	}
   2794 	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
   2795 		error_f("inconsistent flags/output");
   2796 		return 0;
   2797 	}
   2798 
   2799 	/*
   2800 	 * If executing an explicit binary, then verify the it exists
   2801 	 * and appears safe-ish to execute
   2802 	 */
   2803 	if (!path_absolute(av[0])) {
   2804 		error("%s path is not absolute", tag);
   2805 		return 0;
   2806 	}
   2807 	if (drop_privs != NULL)
   2808 		drop_privs(pw);
   2809 	if (stat(av[0], &st) == -1) {
   2810 		error("Could not stat %s \"%s\": %s", tag,
   2811 		    av[0], strerror(errno));
   2812 		goto restore_return;
   2813 	}
   2814 	if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
   2815 	    safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
   2816 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
   2817 		goto restore_return;
   2818 	}
   2819 	/* Prepare to keep the child's stdout if requested */
   2820 	if (pipe(p) == -1) {
   2821 		error("%s: pipe: %s", tag, strerror(errno));
   2822  restore_return:
   2823 		if (restore_privs != NULL)
   2824 			restore_privs();
   2825 		return 0;
   2826 	}
   2827 	if (restore_privs != NULL)
   2828 		restore_privs();
   2829 
   2830 	switch ((pid = fork())) {
   2831 	case -1: /* error */
   2832 		error("%s: fork: %s", tag, strerror(errno));
   2833 		close(p[0]);
   2834 		close(p[1]);
   2835 		return 0;
   2836 	case 0: /* child */
   2837 		/* Prepare a minimal environment for the child. */
   2838 		if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
   2839 			nenv = 5;
   2840 			env = xcalloc(sizeof(*env), nenv);
   2841 			child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
   2842 			child_set_env(&env, &nenv, "USER", pw->pw_name);
   2843 			child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
   2844 			child_set_env(&env, &nenv, "HOME", pw->pw_dir);
   2845 			if ((cp = getenv("LANG")) != NULL)
   2846 				child_set_env(&env, &nenv, "LANG", cp);
   2847 		}
   2848 
   2849 		for (i = 1; i < NSIG; i++)
   2850 			ssh_signal(i, SIG_DFL);
   2851 
   2852 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
   2853 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
   2854 			    strerror(errno));
   2855 			_exit(1);
   2856 		}
   2857 		if (dup2(devnull, STDIN_FILENO) == -1) {
   2858 			error("%s: dup2: %s", tag, strerror(errno));
   2859 			_exit(1);
   2860 		}
   2861 
   2862 		/* Set up stdout as requested; leave stderr in place for now. */
   2863 		fd = -1;
   2864 		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
   2865 			fd = p[1];
   2866 		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
   2867 			fd = devnull;
   2868 		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
   2869 			error("%s: dup2: %s", tag, strerror(errno));
   2870 			_exit(1);
   2871 		}
   2872 		closefrom(STDERR_FILENO + 1);
   2873 
   2874 #ifdef __NetBSD__
   2875 #define setresgid(a, b, c)      setgid(a)
   2876 #define setresuid(a, b, c)      setuid(a)
   2877 #endif
   2878 
   2879 		if (geteuid() == 0 &&
   2880 		    initgroups(pw->pw_name, pw->pw_gid) == -1) {
   2881 			error("%s: initgroups(%s, %u): %s", tag,
   2882 			    pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
   2883 			_exit(1);
   2884 		}
   2885 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
   2886 			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
   2887 			    strerror(errno));
   2888 			_exit(1);
   2889 		}
   2890 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
   2891 			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
   2892 			    strerror(errno));
   2893 			_exit(1);
   2894 		}
   2895 		/* stdin is pointed to /dev/null at this point */
   2896 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
   2897 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
   2898 			error("%s: dup2: %s", tag, strerror(errno));
   2899 			_exit(1);
   2900 		}
   2901 		if (env != NULL)
   2902 			execve(av[0], av, env);
   2903 		else
   2904 			execv(av[0], av);
   2905 		error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
   2906 		    command, strerror(errno));
   2907 		_exit(127);
   2908 	default: /* parent */
   2909 		break;
   2910 	}
   2911 
   2912 	close(p[1]);
   2913 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
   2914 		close(p[0]);
   2915 	else if ((f = fdopen(p[0], "r")) == NULL) {
   2916 		error("%s: fdopen: %s", tag, strerror(errno));
   2917 		close(p[0]);
   2918 		/* Don't leave zombie child */
   2919 		kill(pid, SIGTERM);
   2920 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
   2921 			;
   2922 		return 0;
   2923 	}
   2924 	/* Success */
   2925 	debug3_f("%s pid %ld", tag, (long)pid);
   2926 	if (child != NULL)
   2927 		*child = f;
   2928 	return pid;
   2929 }
   2930 
   2931 const char *
   2932 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
   2933 {
   2934 	size_t i, envlen;
   2935 
   2936 	envlen = strlen(env);
   2937 	for (i = 0; i < nenvs; i++) {
   2938 		if (strncmp(envs[i], env, envlen) == 0 &&
   2939 		    envs[i][envlen] == '=') {
   2940 			return envs[i] + envlen + 1;
   2941 		}
   2942 	}
   2943 	return NULL;
   2944 }
   2945 
   2946 const char *
   2947 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
   2948 {
   2949 	char *name, *cp;
   2950 	const char *ret;
   2951 
   2952 	name = xstrdup(env);
   2953 	if ((cp = strchr(name, '=')) == NULL) {
   2954 		free(name);
   2955 		return NULL; /* not env=val */
   2956 	}
   2957 	*cp = '\0';
   2958 	ret = lookup_env_in_list(name, envs, nenvs);
   2959 	free(name);
   2960 	return ret;
   2961 }
   2962 
   2963 /*
   2964  * Helpers for managing poll(2)/ppoll(2) timeouts
   2965  * Will remember the earliest deadline and return it for use in poll/ppoll.
   2966  */
   2967 
   2968 /* Initialise a poll/ppoll timeout with an indefinite deadline */
   2969 void
   2970 ptimeout_init(struct timespec *pt)
   2971 {
   2972 	/*
   2973 	 * Deliberately invalid for ppoll(2).
   2974 	 * Will be converted to NULL in ptimeout_get_tspec() later.
   2975 	 */
   2976 	pt->tv_sec = -1;
   2977 	pt->tv_nsec = 0;
   2978 }
   2979 
   2980 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
   2981 void
   2982 ptimeout_deadline_sec(struct timespec *pt, long sec)
   2983 {
   2984 	if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
   2985 		pt->tv_sec = sec;
   2986 		pt->tv_nsec = 0;
   2987 	}
   2988 }
   2989 
   2990 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
   2991 static void
   2992 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
   2993 {
   2994 	if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
   2995 		*pt = *p;
   2996 }
   2997 
   2998 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
   2999 void
   3000 ptimeout_deadline_ms(struct timespec *pt, long ms)
   3001 {
   3002 	struct timespec p;
   3003 
   3004 	p.tv_sec = ms / 1000;
   3005 	p.tv_nsec = (ms % 1000) * 1000000;
   3006 	ptimeout_deadline_tsp(pt, &p);
   3007 }
   3008 
   3009 /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
   3010 void
   3011 ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
   3012 {
   3013 	struct timespec now, t;
   3014 
   3015 	monotime_ts(&now);
   3016 
   3017 	if (timespeccmp(&now, when, >=)) {
   3018 		/* 'when' is now or in the past. Timeout ASAP */
   3019 		pt->tv_sec = 0;
   3020 		pt->tv_nsec = 0;
   3021 	} else {
   3022 		timespecsub(when, &now, &t);
   3023 		ptimeout_deadline_tsp(pt, &t);
   3024 	}
   3025 }
   3026 
   3027 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
   3028 void
   3029 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
   3030 {
   3031 	struct timespec t;
   3032 
   3033 	t.tv_sec = when;
   3034 	t.tv_nsec = 0;
   3035 	ptimeout_deadline_monotime_tsp(pt, &t);
   3036 }
   3037 
   3038 /* Get a poll(2) timeout value in milliseconds */
   3039 int
   3040 ptimeout_get_ms(struct timespec *pt)
   3041 {
   3042 	if (pt->tv_sec == -1)
   3043 		return -1;
   3044 	if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
   3045 		return INT_MAX;
   3046 	return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
   3047 }
   3048 
   3049 /* Get a ppoll(2) timeout value as a timespec pointer */
   3050 struct timespec *
   3051 ptimeout_get_tsp(struct timespec *pt)
   3052 {
   3053 	return pt->tv_sec == -1 ? NULL : pt;
   3054 }
   3055 
   3056 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
   3057 int
   3058 ptimeout_isset(struct timespec *pt)
   3059 {
   3060 	return pt->tv_sec != -1;
   3061 }
   3062 
   3063 /*
   3064  * Returns zero if the library at 'path' contains symbol 's', nonzero
   3065  * otherwise.
   3066  */
   3067 int
   3068 lib_contains_symbol(const char *path, const char *s)
   3069 {
   3070 	struct nlist nl[2];
   3071 	int ret = -1, r;
   3072 	char *name;
   3073 
   3074 	memset(nl, 0, sizeof(nl));
   3075 	nl[0].n_name = name = xstrdup(s);
   3076 	nl[1].n_name = NULL;
   3077 	if ((r = nlist(path, nl)) == -1) {
   3078 		error_f("nlist failed for %s", path);
   3079 		goto out;
   3080 	}
   3081 	if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
   3082 		error_f("library %s does not contain symbol %s", path, s);
   3083 		goto out;
   3084 	}
   3085 	/* success */
   3086 	ret = 0;
   3087  out:
   3088 	free(name);
   3089 	return ret;
   3090 }
   3091 
   3092 int
   3093 signal_is_crash(int sig)
   3094 {
   3095 	switch (sig) {
   3096 	case SIGSEGV:
   3097 	case SIGBUS:
   3098 	case SIGTRAP:
   3099 	case SIGSYS:
   3100 	case SIGFPE:
   3101 	case SIGILL:
   3102 	case SIGABRT:
   3103 		return 1;
   3104 	}
   3105 	return 0;
   3106 }
   3107 
   3108 char *
   3109 get_homedir(void)
   3110 {
   3111 	char *cp;
   3112 	struct passwd *pw;
   3113 
   3114 	if ((cp = getenv("HOME")) != NULL && *cp != '\0')
   3115 		return xstrdup(cp);
   3116 
   3117 	if ((pw = getpwuid(getuid())) != NULL && *pw->pw_dir != '\0')
   3118 		return xstrdup(pw->pw_dir);
   3119 
   3120 	return NULL;
   3121 }
   3122