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