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