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