Home | History | Annotate | Line # | Download | only in dist
misc.c revision 1.15
      1  1.15  christos /*	$NetBSD: misc.c,v 1.15 2017/04/18 18:41:46 christos Exp $	*/
      2  1.15  christos /* $OpenBSD: misc.c,v 1.109 2017/03/14 00:55:37 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.8  christos __RCSID("$NetBSD: misc.c,v 1.15 2017/04/18 18:41:46 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.12  christos #include <sys/time.h>
     34   1.9  christos #include <sys/un.h>
     35   1.1  christos 
     36   1.1  christos #include <net/if.h>
     37   1.2  christos #include <net/if_tun.h>
     38   1.1  christos #include <netinet/in.h>
     39   1.5  christos #include <netinet/ip.h>
     40   1.1  christos #include <netinet/tcp.h>
     41   1.1  christos 
     42   1.9  christos #include <ctype.h>
     43   1.1  christos #include <errno.h>
     44   1.1  christos #include <fcntl.h>
     45   1.1  christos #include <netdb.h>
     46   1.1  christos #include <paths.h>
     47   1.1  christos #include <pwd.h>
     48  1.10  christos #include <limits.h>
     49   1.1  christos #include <stdarg.h>
     50   1.1  christos #include <stdio.h>
     51   1.1  christos #include <stdlib.h>
     52   1.1  christos #include <string.h>
     53   1.1  christos #include <unistd.h>
     54   1.1  christos 
     55   1.1  christos #include "xmalloc.h"
     56   1.1  christos #include "misc.h"
     57   1.1  christos #include "log.h"
     58   1.1  christos #include "ssh.h"
     59   1.1  christos 
     60   1.1  christos /* remove newline at end of string */
     61   1.1  christos char *
     62   1.1  christos chop(char *s)
     63   1.1  christos {
     64   1.1  christos 	char *t = s;
     65   1.1  christos 	while (*t) {
     66   1.1  christos 		if (*t == '\n' || *t == '\r') {
     67   1.1  christos 			*t = '\0';
     68   1.1  christos 			return s;
     69   1.1  christos 		}
     70   1.1  christos 		t++;
     71   1.1  christos 	}
     72   1.1  christos 	return s;
     73   1.1  christos 
     74   1.1  christos }
     75   1.1  christos 
     76   1.1  christos /* set/unset filedescriptor to non-blocking */
     77   1.1  christos int
     78   1.1  christos set_nonblock(int fd)
     79   1.1  christos {
     80   1.1  christos 	int val;
     81   1.1  christos 
     82  1.13  christos 	val = fcntl(fd, F_GETFL);
     83   1.1  christos 	if (val < 0) {
     84  1.13  christos 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
     85   1.1  christos 		return (-1);
     86   1.1  christos 	}
     87   1.1  christos 	if (val & O_NONBLOCK) {
     88   1.1  christos 		debug3("fd %d is O_NONBLOCK", fd);
     89   1.1  christos 		return (0);
     90   1.1  christos 	}
     91   1.1  christos 	debug2("fd %d setting O_NONBLOCK", fd);
     92   1.1  christos 	val |= O_NONBLOCK;
     93   1.1  christos 	if (fcntl(fd, F_SETFL, val) == -1) {
     94   1.1  christos 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
     95   1.1  christos 		    strerror(errno));
     96   1.1  christos 		return (-1);
     97   1.1  christos 	}
     98   1.1  christos 	return (0);
     99   1.1  christos }
    100   1.1  christos 
    101   1.1  christos int
    102   1.1  christos unset_nonblock(int fd)
    103   1.1  christos {
    104   1.1  christos 	int val;
    105   1.1  christos 
    106  1.13  christos 	val = fcntl(fd, F_GETFL);
    107   1.1  christos 	if (val < 0) {
    108  1.13  christos 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
    109   1.1  christos 		return (-1);
    110   1.1  christos 	}
    111   1.1  christos 	if (!(val & O_NONBLOCK)) {
    112   1.1  christos 		debug3("fd %d is not O_NONBLOCK", fd);
    113   1.1  christos 		return (0);
    114   1.1  christos 	}
    115   1.1  christos 	debug("fd %d clearing O_NONBLOCK", fd);
    116   1.1  christos 	val &= ~O_NONBLOCK;
    117   1.1  christos 	if (fcntl(fd, F_SETFL, val) == -1) {
    118   1.1  christos 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
    119   1.1  christos 		    fd, strerror(errno));
    120   1.1  christos 		return (-1);
    121   1.1  christos 	}
    122   1.1  christos 	return (0);
    123   1.1  christos }
    124   1.1  christos 
    125   1.1  christos const char *
    126   1.1  christos ssh_gai_strerror(int gaierr)
    127   1.1  christos {
    128   1.8  christos 	if (gaierr == EAI_SYSTEM && errno != 0)
    129   1.1  christos 		return strerror(errno);
    130   1.1  christos 	return gai_strerror(gaierr);
    131   1.1  christos }
    132   1.1  christos 
    133   1.1  christos /* disable nagle on socket */
    134   1.1  christos void
    135   1.1  christos set_nodelay(int fd)
    136   1.1  christos {
    137   1.1  christos 	int opt;
    138   1.1  christos 	socklen_t optlen;
    139   1.1  christos 
    140   1.1  christos 	optlen = sizeof opt;
    141   1.1  christos 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
    142   1.1  christos 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
    143   1.1  christos 		return;
    144   1.1  christos 	}
    145   1.1  christos 	if (opt == 1) {
    146   1.1  christos 		debug2("fd %d is TCP_NODELAY", fd);
    147   1.1  christos 		return;
    148   1.1  christos 	}
    149   1.1  christos 	opt = 1;
    150   1.1  christos 	debug2("fd %d setting TCP_NODELAY", fd);
    151   1.1  christos 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
    152   1.1  christos 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
    153   1.1  christos }
    154   1.1  christos 
    155   1.1  christos /* Characters considered whitespace in strsep calls. */
    156   1.1  christos #define WHITESPACE " \t\r\n"
    157   1.1  christos #define QUOTE	"\""
    158   1.1  christos 
    159   1.1  christos /* return next token in configuration line */
    160   1.1  christos char *
    161   1.1  christos strdelim(char **s)
    162   1.1  christos {
    163   1.1  christos 	char *old;
    164   1.1  christos 	int wspace = 0;
    165   1.1  christos 
    166   1.1  christos 	if (*s == NULL)
    167   1.1  christos 		return NULL;
    168   1.1  christos 
    169   1.1  christos 	old = *s;
    170   1.1  christos 
    171   1.1  christos 	*s = strpbrk(*s, WHITESPACE QUOTE "=");
    172   1.1  christos 	if (*s == NULL)
    173   1.1  christos 		return (old);
    174   1.1  christos 
    175   1.1  christos 	if (*s[0] == '\"') {
    176   1.1  christos 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
    177   1.1  christos 		/* Find matching quote */
    178   1.1  christos 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
    179   1.1  christos 			return (NULL);		/* no matching quote */
    180   1.1  christos 		} else {
    181   1.1  christos 			*s[0] = '\0';
    182   1.4      adam 			*s += strspn(*s + 1, WHITESPACE) + 1;
    183   1.1  christos 			return (old);
    184   1.1  christos 		}
    185   1.1  christos 	}
    186   1.1  christos 
    187   1.1  christos 	/* Allow only one '=' to be skipped */
    188   1.1  christos 	if (*s[0] == '=')
    189   1.1  christos 		wspace = 1;
    190   1.1  christos 	*s[0] = '\0';
    191   1.1  christos 
    192   1.1  christos 	/* Skip any extra whitespace after first token */
    193   1.1  christos 	*s += strspn(*s + 1, WHITESPACE) + 1;
    194   1.1  christos 	if (*s[0] == '=' && !wspace)
    195   1.1  christos 		*s += strspn(*s + 1, WHITESPACE) + 1;
    196   1.1  christos 
    197   1.1  christos 	return (old);
    198   1.1  christos }
    199   1.1  christos 
    200   1.1  christos struct passwd *
    201   1.1  christos pwcopy(struct passwd *pw)
    202   1.1  christos {
    203   1.1  christos 	struct passwd *copy = xcalloc(1, sizeof(*copy));
    204   1.1  christos 
    205   1.1  christos 	copy->pw_name = xstrdup(pw->pw_name);
    206   1.1  christos 	copy->pw_passwd = xstrdup(pw->pw_passwd);
    207   1.1  christos 	copy->pw_gecos = xstrdup(pw->pw_gecos);
    208   1.1  christos 	copy->pw_uid = pw->pw_uid;
    209   1.1  christos 	copy->pw_gid = pw->pw_gid;
    210   1.1  christos 	copy->pw_expire = pw->pw_expire;
    211   1.1  christos 	copy->pw_change = pw->pw_change;
    212   1.1  christos 	copy->pw_class = xstrdup(pw->pw_class);
    213   1.1  christos 	copy->pw_dir = xstrdup(pw->pw_dir);
    214   1.1  christos 	copy->pw_shell = xstrdup(pw->pw_shell);
    215   1.1  christos 	return copy;
    216   1.1  christos }
    217   1.1  christos 
    218   1.1  christos /*
    219   1.1  christos  * Convert ASCII string to TCP/IP port number.
    220   1.1  christos  * Port must be >=0 and <=65535.
    221   1.1  christos  * Return -1 if invalid.
    222   1.1  christos  */
    223   1.1  christos int
    224   1.1  christos a2port(const char *s)
    225   1.1  christos {
    226   1.1  christos 	long long port;
    227   1.1  christos 	const char *errstr;
    228   1.1  christos 
    229   1.1  christos 	port = strtonum(s, 0, 65535, &errstr);
    230   1.1  christos 	if (errstr != NULL)
    231   1.1  christos 		return -1;
    232   1.1  christos 	return (int)port;
    233   1.1  christos }
    234   1.1  christos 
    235   1.1  christos int
    236   1.1  christos a2tun(const char *s, int *remote)
    237   1.1  christos {
    238   1.1  christos 	const char *errstr = NULL;
    239   1.1  christos 	char *sp, *ep;
    240   1.1  christos 	int tun;
    241   1.1  christos 
    242   1.1  christos 	if (remote != NULL) {
    243   1.1  christos 		*remote = SSH_TUNID_ANY;
    244   1.1  christos 		sp = xstrdup(s);
    245   1.1  christos 		if ((ep = strchr(sp, ':')) == NULL) {
    246   1.8  christos 			free(sp);
    247   1.1  christos 			return (a2tun(s, NULL));
    248   1.1  christos 		}
    249   1.1  christos 		ep[0] = '\0'; ep++;
    250   1.1  christos 		*remote = a2tun(ep, NULL);
    251   1.1  christos 		tun = a2tun(sp, NULL);
    252   1.8  christos 		free(sp);
    253   1.1  christos 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
    254   1.1  christos 	}
    255   1.1  christos 
    256   1.1  christos 	if (strcasecmp(s, "any") == 0)
    257   1.1  christos 		return (SSH_TUNID_ANY);
    258   1.1  christos 
    259   1.1  christos 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
    260   1.1  christos 	if (errstr != NULL)
    261   1.1  christos 		return (SSH_TUNID_ERR);
    262   1.1  christos 
    263   1.1  christos 	return (tun);
    264   1.1  christos }
    265   1.1  christos 
    266   1.1  christos #define SECONDS		1
    267   1.1  christos #define MINUTES		(SECONDS * 60)
    268   1.1  christos #define HOURS		(MINUTES * 60)
    269   1.1  christos #define DAYS		(HOURS * 24)
    270   1.1  christos #define WEEKS		(DAYS * 7)
    271   1.1  christos 
    272   1.1  christos /*
    273   1.1  christos  * Convert a time string into seconds; format is
    274   1.1  christos  * a sequence of:
    275   1.1  christos  *      time[qualifier]
    276   1.1  christos  *
    277   1.1  christos  * Valid time qualifiers are:
    278   1.1  christos  *      <none>  seconds
    279   1.1  christos  *      s|S     seconds
    280   1.1  christos  *      m|M     minutes
    281   1.1  christos  *      h|H     hours
    282   1.1  christos  *      d|D     days
    283   1.1  christos  *      w|W     weeks
    284   1.1  christos  *
    285   1.1  christos  * Examples:
    286   1.1  christos  *      90m     90 minutes
    287   1.1  christos  *      1h30m   90 minutes
    288   1.1  christos  *      2d      2 days
    289   1.1  christos  *      1w      1 week
    290   1.1  christos  *
    291   1.1  christos  * Return -1 if time string is invalid.
    292   1.1  christos  */
    293   1.1  christos long
    294   1.1  christos convtime(const char *s)
    295   1.1  christos {
    296  1.15  christos 	long total, secs, multiplier = 1;
    297   1.1  christos 	const char *p;
    298   1.1  christos 	char *endp;
    299   1.1  christos 
    300   1.1  christos 	errno = 0;
    301   1.1  christos 	total = 0;
    302   1.1  christos 	p = s;
    303   1.1  christos 
    304   1.1  christos 	if (p == NULL || *p == '\0')
    305   1.1  christos 		return -1;
    306   1.1  christos 
    307   1.1  christos 	while (*p) {
    308   1.1  christos 		secs = strtol(p, &endp, 10);
    309   1.1  christos 		if (p == endp ||
    310   1.1  christos 		    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
    311   1.1  christos 		    secs < 0)
    312   1.1  christos 			return -1;
    313   1.1  christos 
    314   1.1  christos 		switch (*endp++) {
    315   1.1  christos 		case '\0':
    316   1.1  christos 			endp--;
    317   1.1  christos 			break;
    318   1.1  christos 		case 's':
    319   1.1  christos 		case 'S':
    320   1.1  christos 			break;
    321   1.1  christos 		case 'm':
    322   1.1  christos 		case 'M':
    323  1.15  christos 			multiplier = MINUTES;
    324   1.1  christos 			break;
    325   1.1  christos 		case 'h':
    326   1.1  christos 		case 'H':
    327  1.15  christos 			multiplier = HOURS;
    328   1.1  christos 			break;
    329   1.1  christos 		case 'd':
    330   1.1  christos 		case 'D':
    331  1.15  christos 			multiplier = DAYS;
    332   1.1  christos 			break;
    333   1.1  christos 		case 'w':
    334   1.1  christos 		case 'W':
    335  1.15  christos 			multiplier = WEEKS;
    336   1.1  christos 			break;
    337   1.1  christos 		default:
    338   1.1  christos 			return -1;
    339   1.1  christos 		}
    340  1.15  christos 		if (secs >= LONG_MAX / multiplier)
    341  1.15  christos 			return -1;
    342  1.15  christos 		secs *= multiplier;
    343  1.15  christos 		if  (total >= LONG_MAX - secs)
    344  1.15  christos 			return -1;
    345   1.1  christos 		total += secs;
    346   1.1  christos 		if (total < 0)
    347   1.1  christos 			return -1;
    348   1.1  christos 		p = endp;
    349   1.1  christos 	}
    350   1.1  christos 
    351   1.1  christos 	return total;
    352   1.1  christos }
    353   1.1  christos 
    354   1.1  christos /*
    355   1.1  christos  * Returns a standardized host+port identifier string.
    356   1.1  christos  * Caller must free returned string.
    357   1.1  christos  */
    358   1.1  christos char *
    359   1.1  christos put_host_port(const char *host, u_short port)
    360   1.1  christos {
    361   1.1  christos 	char *hoststr;
    362   1.1  christos 
    363   1.1  christos 	if (port == 0 || port == SSH_DEFAULT_PORT)
    364   1.1  christos 		return(xstrdup(host));
    365   1.1  christos 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
    366   1.1  christos 		fatal("put_host_port: asprintf: %s", strerror(errno));
    367   1.1  christos 	debug3("put_host_port: %s", hoststr);
    368   1.1  christos 	return hoststr;
    369   1.1  christos }
    370   1.1  christos 
    371   1.1  christos /*
    372   1.1  christos  * Search for next delimiter between hostnames/addresses and ports.
    373   1.1  christos  * Argument may be modified (for termination).
    374   1.1  christos  * Returns *cp if parsing succeeds.
    375   1.1  christos  * *cp is set to the start of the next delimiter, if one was found.
    376   1.1  christos  * If this is the last field, *cp is set to NULL.
    377   1.1  christos  */
    378   1.1  christos char *
    379   1.1  christos hpdelim(char **cp)
    380   1.1  christos {
    381   1.1  christos 	char *s, *old;
    382   1.1  christos 
    383   1.1  christos 	if (cp == NULL || *cp == NULL)
    384   1.1  christos 		return NULL;
    385   1.1  christos 
    386   1.1  christos 	old = s = *cp;
    387   1.1  christos 	if (*s == '[') {
    388   1.1  christos 		if ((s = strchr(s, ']')) == NULL)
    389   1.1  christos 			return NULL;
    390   1.1  christos 		else
    391   1.1  christos 			s++;
    392   1.1  christos 	} else if ((s = strpbrk(s, ":/")) == NULL)
    393   1.1  christos 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
    394   1.1  christos 
    395   1.1  christos 	switch (*s) {
    396   1.1  christos 	case '\0':
    397   1.1  christos 		*cp = NULL;	/* no more fields*/
    398   1.1  christos 		break;
    399   1.1  christos 
    400   1.1  christos 	case ':':
    401   1.1  christos 	case '/':
    402   1.1  christos 		*s = '\0';	/* terminate */
    403   1.1  christos 		*cp = s + 1;
    404   1.1  christos 		break;
    405   1.1  christos 
    406   1.1  christos 	default:
    407   1.1  christos 		return NULL;
    408   1.1  christos 	}
    409   1.1  christos 
    410   1.1  christos 	return old;
    411   1.1  christos }
    412   1.1  christos 
    413   1.1  christos char *
    414   1.1  christos cleanhostname(char *host)
    415   1.1  christos {
    416   1.1  christos 	if (*host == '[' && host[strlen(host) - 1] == ']') {
    417   1.1  christos 		host[strlen(host) - 1] = '\0';
    418   1.1  christos 		return (host + 1);
    419   1.1  christos 	} else
    420   1.1  christos 		return host;
    421   1.1  christos }
    422   1.1  christos 
    423   1.1  christos char *
    424   1.1  christos colon(char *cp)
    425   1.1  christos {
    426   1.1  christos 	int flag = 0;
    427   1.1  christos 
    428   1.1  christos 	if (*cp == ':')		/* Leading colon is part of file name. */
    429   1.4      adam 		return NULL;
    430   1.1  christos 	if (*cp == '[')
    431   1.1  christos 		flag = 1;
    432   1.1  christos 
    433   1.1  christos 	for (; *cp; ++cp) {
    434   1.1  christos 		if (*cp == '@' && *(cp+1) == '[')
    435   1.1  christos 			flag = 1;
    436   1.1  christos 		if (*cp == ']' && *(cp+1) == ':' && flag)
    437   1.1  christos 			return (cp+1);
    438   1.1  christos 		if (*cp == ':' && !flag)
    439   1.1  christos 			return (cp);
    440   1.1  christos 		if (*cp == '/')
    441   1.4      adam 			return NULL;
    442   1.1  christos 	}
    443   1.4      adam 	return NULL;
    444   1.1  christos }
    445   1.1  christos 
    446  1.13  christos /*
    447  1.13  christos  * Parse a [user@]host[:port] string.
    448  1.13  christos  * Caller must free returned user and host.
    449  1.13  christos  * Any of the pointer return arguments may be NULL (useful for syntax checking).
    450  1.13  christos  * If user was not specified then *userp will be set to NULL.
    451  1.13  christos  * If port was not specified then *portp will be -1.
    452  1.13  christos  * Returns 0 on success, -1 on failure.
    453  1.13  christos  */
    454  1.13  christos int
    455  1.13  christos parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
    456  1.13  christos {
    457  1.13  christos 	char *sdup, *cp, *tmp;
    458  1.13  christos 	char *user = NULL, *host = NULL;
    459  1.13  christos 	int port = -1, ret = -1;
    460  1.13  christos 
    461  1.13  christos 	if (userp != NULL)
    462  1.13  christos 		*userp = NULL;
    463  1.13  christos 	if (hostp != NULL)
    464  1.13  christos 		*hostp = NULL;
    465  1.13  christos 	if (portp != NULL)
    466  1.13  christos 		*portp = -1;
    467  1.13  christos 
    468  1.13  christos 	if ((sdup = tmp = strdup(s)) == NULL)
    469  1.13  christos 		return -1;
    470  1.13  christos 	/* Extract optional username */
    471  1.13  christos 	if ((cp = strchr(tmp, '@')) != NULL) {
    472  1.13  christos 		*cp = '\0';
    473  1.13  christos 		if (*tmp == '\0')
    474  1.13  christos 			goto out;
    475  1.13  christos 		if ((user = strdup(tmp)) == NULL)
    476  1.13  christos 			goto out;
    477  1.13  christos 		tmp = cp + 1;
    478  1.13  christos 	}
    479  1.13  christos 	/* Extract mandatory hostname */
    480  1.13  christos 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
    481  1.13  christos 		goto out;
    482  1.13  christos 	host = xstrdup(cleanhostname(cp));
    483  1.13  christos 	/* Convert and verify optional port */
    484  1.13  christos 	if (tmp != NULL && *tmp != '\0') {
    485  1.13  christos 		if ((port = a2port(tmp)) <= 0)
    486  1.13  christos 			goto out;
    487  1.13  christos 	}
    488  1.13  christos 	/* Success */
    489  1.13  christos 	if (userp != NULL) {
    490  1.13  christos 		*userp = user;
    491  1.13  christos 		user = NULL;
    492  1.13  christos 	}
    493  1.13  christos 	if (hostp != NULL) {
    494  1.13  christos 		*hostp = host;
    495  1.13  christos 		host = NULL;
    496  1.13  christos 	}
    497  1.13  christos 	if (portp != NULL)
    498  1.13  christos 		*portp = port;
    499  1.13  christos 	ret = 0;
    500  1.13  christos  out:
    501  1.13  christos 	free(sdup);
    502  1.13  christos 	free(user);
    503  1.13  christos 	free(host);
    504  1.13  christos 	return ret;
    505  1.13  christos }
    506  1.13  christos 
    507   1.1  christos /* function to assist building execv() arguments */
    508   1.1  christos void
    509   1.5  christos addargs(arglist *args, const char *fmt, ...)
    510   1.1  christos {
    511   1.1  christos 	va_list ap;
    512   1.1  christos 	char *cp;
    513   1.1  christos 	u_int nalloc;
    514   1.1  christos 	int r;
    515   1.1  christos 
    516   1.1  christos 	va_start(ap, fmt);
    517   1.1  christos 	r = vasprintf(&cp, fmt, ap);
    518   1.1  christos 	va_end(ap);
    519   1.1  christos 	if (r == -1)
    520   1.1  christos 		fatal("addargs: argument too long");
    521   1.1  christos 
    522   1.1  christos 	nalloc = args->nalloc;
    523   1.1  christos 	if (args->list == NULL) {
    524   1.1  christos 		nalloc = 32;
    525   1.1  christos 		args->num = 0;
    526   1.1  christos 	} else if (args->num+2 >= nalloc)
    527   1.1  christos 		nalloc *= 2;
    528   1.1  christos 
    529  1.11  christos 	args->list = xreallocarray(args->list, nalloc, sizeof(char *));
    530   1.1  christos 	args->nalloc = nalloc;
    531   1.1  christos 	args->list[args->num++] = cp;
    532   1.1  christos 	args->list[args->num] = NULL;
    533   1.1  christos }
    534   1.1  christos 
    535   1.1  christos void
    536   1.5  christos replacearg(arglist *args, u_int which, const char *fmt, ...)
    537   1.1  christos {
    538   1.1  christos 	va_list ap;
    539   1.1  christos 	char *cp;
    540   1.1  christos 	int r;
    541   1.1  christos 
    542   1.1  christos 	va_start(ap, fmt);
    543   1.1  christos 	r = vasprintf(&cp, fmt, ap);
    544   1.1  christos 	va_end(ap);
    545   1.1  christos 	if (r == -1)
    546   1.1  christos 		fatal("replacearg: argument too long");
    547   1.1  christos 
    548   1.1  christos 	if (which >= args->num)
    549   1.1  christos 		fatal("replacearg: tried to replace invalid arg %d >= %d",
    550   1.1  christos 		    which, args->num);
    551   1.8  christos 	free(args->list[which]);
    552   1.1  christos 	args->list[which] = cp;
    553   1.1  christos }
    554   1.1  christos 
    555   1.1  christos void
    556   1.1  christos freeargs(arglist *args)
    557   1.1  christos {
    558   1.1  christos 	u_int i;
    559   1.1  christos 
    560   1.1  christos 	if (args->list != NULL) {
    561   1.1  christos 		for (i = 0; i < args->num; i++)
    562   1.8  christos 			free(args->list[i]);
    563   1.8  christos 		free(args->list);
    564   1.1  christos 		args->nalloc = args->num = 0;
    565   1.1  christos 		args->list = NULL;
    566   1.1  christos 	}
    567   1.1  christos }
    568   1.1  christos 
    569   1.1  christos /*
    570   1.1  christos  * Expands tildes in the file name.  Returns data allocated by xmalloc.
    571   1.1  christos  * Warning: this calls getpw*.
    572   1.1  christos  */
    573   1.1  christos char *
    574   1.1  christos tilde_expand_filename(const char *filename, uid_t uid)
    575   1.1  christos {
    576   1.8  christos 	const char *path, *sep;
    577   1.8  christos 	char user[128], *ret, *homedir;
    578   1.1  christos 	struct passwd *pw;
    579   1.1  christos 	u_int len, slash;
    580   1.1  christos 
    581   1.1  christos 	if (*filename != '~')
    582   1.1  christos 		return (xstrdup(filename));
    583   1.1  christos 	filename++;
    584   1.1  christos 
    585   1.1  christos 	path = strchr(filename, '/');
    586   1.1  christos 	if (path != NULL && path > filename) {		/* ~user/path */
    587   1.1  christos 		slash = path - filename;
    588   1.1  christos 		if (slash > sizeof(user) - 1)
    589   1.1  christos 			fatal("tilde_expand_filename: ~username too long");
    590   1.1  christos 		memcpy(user, filename, slash);
    591   1.1  christos 		user[slash] = '\0';
    592   1.1  christos 		if ((pw = getpwnam(user)) == NULL)
    593   1.1  christos 			fatal("tilde_expand_filename: No such user %s", user);
    594   1.2  christos 		homedir = pw->pw_dir;
    595   1.2  christos 	} else {
    596   1.2  christos 		if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
    597   1.2  christos 			fatal("tilde_expand_filename: No such uid %ld",
    598   1.2  christos 			    (long)uid);
    599   1.2  christos 		homedir = pw->pw_dir;
    600   1.2  christos 	}
    601   1.1  christos 
    602   1.1  christos 	/* Make sure directory has a trailing '/' */
    603   1.2  christos 	len = strlen(homedir);
    604   1.8  christos 	if (len == 0 || homedir[len - 1] != '/')
    605   1.8  christos 		sep = "/";
    606   1.8  christos 	else
    607   1.8  christos 		sep = "";
    608   1.1  christos 
    609   1.1  christos 	/* Skip leading '/' from specified path */
    610   1.1  christos 	if (path != NULL)
    611   1.1  christos 		filename = path + 1;
    612   1.8  christos 
    613  1.10  christos 	if (xasprintf(&ret, "%s%s%s", homedir, sep, filename) >= PATH_MAX)
    614   1.1  christos 		fatal("tilde_expand_filename: Path too long");
    615   1.1  christos 
    616   1.8  christos 	return (ret);
    617   1.1  christos }
    618   1.1  christos 
    619   1.1  christos /*
    620   1.1  christos  * Expand a string with a set of %[char] escapes. A number of escapes may be
    621   1.1  christos  * specified as (char *escape_chars, char *replacement) pairs. The list must
    622   1.1  christos  * be terminated by a NULL escape_char. Returns replaced string in memory
    623   1.1  christos  * allocated by xmalloc.
    624   1.1  christos  */
    625   1.1  christos char *
    626   1.1  christos percent_expand(const char *string, ...)
    627   1.1  christos {
    628   1.1  christos #define EXPAND_MAX_KEYS	16
    629   1.4      adam 	u_int num_keys, i, j;
    630   1.1  christos 	struct {
    631   1.1  christos 		const char *key;
    632   1.1  christos 		const char *repl;
    633   1.1  christos 	} keys[EXPAND_MAX_KEYS];
    634   1.1  christos 	char buf[4096];
    635   1.1  christos 	va_list ap;
    636   1.1  christos 
    637   1.1  christos 	/* Gather keys */
    638   1.1  christos 	va_start(ap, string);
    639   1.1  christos 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
    640   1.1  christos 		keys[num_keys].key = va_arg(ap, char *);
    641   1.1  christos 		if (keys[num_keys].key == NULL)
    642   1.1  christos 			break;
    643   1.1  christos 		keys[num_keys].repl = va_arg(ap, char *);
    644   1.1  christos 		if (keys[num_keys].repl == NULL)
    645   1.4      adam 			fatal("%s: NULL replacement", __func__);
    646   1.1  christos 	}
    647   1.4      adam 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
    648   1.4      adam 		fatal("%s: too many keys", __func__);
    649   1.1  christos 	va_end(ap);
    650   1.1  christos 
    651   1.1  christos 	/* Expand string */
    652   1.1  christos 	*buf = '\0';
    653   1.1  christos 	for (i = 0; *string != '\0'; string++) {
    654   1.1  christos 		if (*string != '%') {
    655   1.1  christos  append:
    656   1.1  christos 			buf[i++] = *string;
    657   1.1  christos 			if (i >= sizeof(buf))
    658   1.4      adam 				fatal("%s: string too long", __func__);
    659   1.1  christos 			buf[i] = '\0';
    660   1.1  christos 			continue;
    661   1.1  christos 		}
    662   1.1  christos 		string++;
    663   1.4      adam 		/* %% case */
    664   1.1  christos 		if (*string == '%')
    665   1.1  christos 			goto append;
    666  1.12  christos 		if (*string == '\0')
    667  1.12  christos 			fatal("%s: invalid format", __func__);
    668   1.1  christos 		for (j = 0; j < num_keys; j++) {
    669   1.1  christos 			if (strchr(keys[j].key, *string) != NULL) {
    670   1.1  christos 				i = strlcat(buf, keys[j].repl, sizeof(buf));
    671   1.1  christos 				if (i >= sizeof(buf))
    672   1.4      adam 					fatal("%s: string too long", __func__);
    673   1.1  christos 				break;
    674   1.1  christos 			}
    675   1.1  christos 		}
    676   1.1  christos 		if (j >= num_keys)
    677   1.4      adam 			fatal("%s: unknown key %%%c", __func__, *string);
    678   1.1  christos 	}
    679   1.1  christos 	return (xstrdup(buf));
    680   1.1  christos #undef EXPAND_MAX_KEYS
    681   1.1  christos }
    682   1.1  christos 
    683   1.1  christos /*
    684   1.1  christos  * Read an entire line from a public key file into a static buffer, discarding
    685   1.1  christos  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
    686   1.1  christos  */
    687   1.1  christos int
    688   1.1  christos read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
    689   1.1  christos    u_long *lineno)
    690   1.1  christos {
    691   1.1  christos 	while (fgets(buf, bufsz, f) != NULL) {
    692   1.1  christos 		if (buf[0] == '\0')
    693   1.1  christos 			continue;
    694   1.1  christos 		(*lineno)++;
    695   1.1  christos 		if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
    696   1.1  christos 			return 0;
    697   1.1  christos 		} else {
    698   1.1  christos 			debug("%s: %s line %lu exceeds size limit", __func__,
    699   1.1  christos 			    filename, *lineno);
    700   1.1  christos 			/* discard remainder of line */
    701   1.1  christos 			while (fgetc(f) != '\n' && !feof(f))
    702   1.1  christos 				;	/* nothing */
    703   1.1  christos 		}
    704   1.1  christos 	}
    705   1.1  christos 	return -1;
    706   1.1  christos }
    707   1.1  christos 
    708   1.1  christos int
    709   1.1  christos tun_open(int tun, int mode)
    710   1.1  christos {
    711   1.1  christos 	struct ifreq ifr;
    712  1.12  christos 	char name[100];
    713  1.12  christos 	int fd = -1, sock;
    714  1.12  christos 	const char *tunbase = "tun";
    715  1.12  christos 
    716  1.12  christos 	if (mode == SSH_TUNMODE_ETHERNET)
    717  1.12  christos 		tunbase = "tap";
    718   1.1  christos 
    719   1.1  christos 	/* Open the tunnel device */
    720   1.1  christos 	if (tun <= SSH_TUNID_MAX) {
    721  1.12  christos 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
    722  1.12  christos 		fd = open(name, O_RDWR);
    723   1.1  christos 	} else if (tun == SSH_TUNID_ANY) {
    724   1.1  christos 		for (tun = 100; tun >= 0; tun--) {
    725  1.12  christos 			snprintf(name, sizeof(name), "/dev/%s%d",
    726  1.12  christos 			    tunbase, tun);
    727  1.12  christos 			if ((fd = open(name, O_RDWR)) >= 0)
    728   1.1  christos 				break;
    729   1.1  christos 		}
    730   1.1  christos 	} else {
    731   1.1  christos 		debug("%s: invalid tunnel %u", __func__, tun);
    732  1.12  christos 		return -1;
    733   1.1  christos 	}
    734   1.1  christos 
    735   1.1  christos 	if (fd < 0) {
    736  1.12  christos 		debug("%s: %s open: %s", __func__, name, strerror(errno));
    737  1.12  christos 		return -1;
    738   1.1  christos 	}
    739   1.1  christos 
    740   1.1  christos 
    741  1.12  christos #ifdef TUNSIFHEAD
    742   1.2  christos 	/* Turn on tunnel headers */
    743  1.12  christos 	int flag = 1;
    744   1.2  christos 	if (mode != SSH_TUNMODE_ETHERNET &&
    745   1.2  christos 	    ioctl(fd, TUNSIFHEAD, &flag) == -1) {
    746   1.2  christos 		debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__, fd,
    747   1.2  christos 		    strerror(errno));
    748   1.2  christos 		close(fd);
    749   1.2  christos 		return -1;
    750   1.2  christos 	}
    751  1.12  christos #endif
    752   1.2  christos 
    753   1.2  christos 	debug("%s: %s mode %d fd %d", __func__, ifr.ifr_name, mode, fd);
    754  1.12  christos 	/* Bring interface up if it is not already */
    755   1.3   jnemeth 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
    756   1.1  christos 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
    757   1.1  christos 		goto failed;
    758   1.1  christos 
    759  1.12  christos 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
    760  1.12  christos 		debug("%s: get interface %s flags: %s", __func__,
    761  1.12  christos 		    ifr.ifr_name, strerror(errno));
    762   1.1  christos 		goto failed;
    763  1.12  christos 	}
    764   1.1  christos 
    765  1.12  christos 	if (!(ifr.ifr_flags & IFF_UP)) {
    766  1.12  christos 		ifr.ifr_flags |= IFF_UP;
    767  1.12  christos 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
    768  1.12  christos 			debug("%s: activate interface %s: %s", __func__,
    769  1.12  christos 			    ifr.ifr_name, strerror(errno));
    770  1.12  christos 			goto failed;
    771  1.12  christos 		}
    772  1.12  christos 	}
    773   1.1  christos 
    774   1.1  christos 	close(sock);
    775  1.12  christos 	return fd;
    776   1.1  christos 
    777   1.1  christos  failed:
    778   1.1  christos 	if (fd >= 0)
    779   1.1  christos 		close(fd);
    780   1.1  christos 	if (sock >= 0)
    781   1.1  christos 		close(sock);
    782   1.2  christos 	debug("%s: failed to set %s mode %d: %s", __func__, ifr.ifr_name,
    783   1.1  christos 	    mode, strerror(errno));
    784  1.12  christos 	return -1;
    785   1.1  christos }
    786   1.1  christos 
    787   1.1  christos void
    788   1.1  christos sanitise_stdfd(void)
    789   1.1  christos {
    790   1.1  christos 	int nullfd, dupfd;
    791   1.1  christos 
    792   1.1  christos 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
    793   1.1  christos 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
    794   1.1  christos 		    strerror(errno));
    795   1.1  christos 		exit(1);
    796   1.1  christos 	}
    797  1.13  christos 	while (++dupfd <= STDERR_FILENO) {
    798  1.13  christos 		/* Only populate closed fds. */
    799  1.13  christos 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
    800  1.13  christos 			if (dup2(nullfd, dupfd) == -1) {
    801  1.13  christos 				fprintf(stderr, "dup2: %s\n", strerror(errno));
    802  1.13  christos 				exit(1);
    803  1.13  christos 			}
    804   1.1  christos 		}
    805   1.1  christos 	}
    806  1.13  christos 	if (nullfd > STDERR_FILENO)
    807   1.1  christos 		close(nullfd);
    808   1.1  christos }
    809   1.1  christos 
    810   1.1  christos char *
    811   1.1  christos tohex(const void *vp, size_t l)
    812   1.1  christos {
    813   1.1  christos 	const u_char *p = (const u_char *)vp;
    814   1.1  christos 	char b[3], *r;
    815   1.1  christos 	size_t i, hl;
    816   1.1  christos 
    817   1.1  christos 	if (l > 65536)
    818   1.1  christos 		return xstrdup("tohex: length > 65536");
    819   1.1  christos 
    820   1.1  christos 	hl = l * 2 + 1;
    821   1.1  christos 	r = xcalloc(1, hl);
    822   1.1  christos 	for (i = 0; i < l; i++) {
    823   1.1  christos 		snprintf(b, sizeof(b), "%02x", p[i]);
    824   1.1  christos 		strlcat(r, b, hl);
    825   1.1  christos 	}
    826   1.1  christos 	return (r);
    827   1.1  christos }
    828   1.1  christos 
    829   1.1  christos u_int64_t
    830   1.1  christos get_u64(const void *vp)
    831   1.1  christos {
    832   1.1  christos 	const u_char *p = (const u_char *)vp;
    833   1.1  christos 	u_int64_t v;
    834   1.1  christos 
    835   1.1  christos 	v  = (u_int64_t)p[0] << 56;
    836   1.1  christos 	v |= (u_int64_t)p[1] << 48;
    837   1.1  christos 	v |= (u_int64_t)p[2] << 40;
    838   1.1  christos 	v |= (u_int64_t)p[3] << 32;
    839   1.1  christos 	v |= (u_int64_t)p[4] << 24;
    840   1.1  christos 	v |= (u_int64_t)p[5] << 16;
    841   1.1  christos 	v |= (u_int64_t)p[6] << 8;
    842   1.1  christos 	v |= (u_int64_t)p[7];
    843   1.1  christos 
    844   1.1  christos 	return (v);
    845   1.1  christos }
    846   1.1  christos 
    847   1.1  christos u_int32_t
    848   1.1  christos get_u32(const void *vp)
    849   1.1  christos {
    850   1.1  christos 	const u_char *p = (const u_char *)vp;
    851   1.1  christos 	u_int32_t v;
    852   1.1  christos 
    853   1.1  christos 	v  = (u_int32_t)p[0] << 24;
    854   1.1  christos 	v |= (u_int32_t)p[1] << 16;
    855   1.1  christos 	v |= (u_int32_t)p[2] << 8;
    856   1.1  christos 	v |= (u_int32_t)p[3];
    857   1.1  christos 
    858   1.1  christos 	return (v);
    859   1.1  christos }
    860   1.1  christos 
    861   1.9  christos u_int32_t
    862   1.9  christos get_u32_le(const void *vp)
    863   1.9  christos {
    864   1.9  christos 	const u_char *p = (const u_char *)vp;
    865   1.9  christos 	u_int32_t v;
    866   1.9  christos 
    867   1.9  christos 	v  = (u_int32_t)p[0];
    868   1.9  christos 	v |= (u_int32_t)p[1] << 8;
    869   1.9  christos 	v |= (u_int32_t)p[2] << 16;
    870   1.9  christos 	v |= (u_int32_t)p[3] << 24;
    871   1.9  christos 
    872   1.9  christos 	return (v);
    873   1.9  christos }
    874   1.9  christos 
    875   1.1  christos u_int16_t
    876   1.1  christos get_u16(const void *vp)
    877   1.1  christos {
    878   1.1  christos 	const u_char *p = (const u_char *)vp;
    879   1.1  christos 	u_int16_t v;
    880   1.1  christos 
    881   1.1  christos 	v  = (u_int16_t)p[0] << 8;
    882   1.1  christos 	v |= (u_int16_t)p[1];
    883   1.1  christos 
    884   1.1  christos 	return (v);
    885   1.1  christos }
    886   1.1  christos 
    887   1.1  christos void
    888   1.1  christos put_u64(void *vp, u_int64_t v)
    889   1.1  christos {
    890   1.1  christos 	u_char *p = (u_char *)vp;
    891   1.1  christos 
    892   1.1  christos 	p[0] = (u_char)(v >> 56) & 0xff;
    893   1.1  christos 	p[1] = (u_char)(v >> 48) & 0xff;
    894   1.1  christos 	p[2] = (u_char)(v >> 40) & 0xff;
    895   1.1  christos 	p[3] = (u_char)(v >> 32) & 0xff;
    896   1.1  christos 	p[4] = (u_char)(v >> 24) & 0xff;
    897   1.1  christos 	p[5] = (u_char)(v >> 16) & 0xff;
    898   1.1  christos 	p[6] = (u_char)(v >> 8) & 0xff;
    899   1.1  christos 	p[7] = (u_char)v & 0xff;
    900   1.1  christos }
    901   1.1  christos 
    902   1.1  christos void
    903   1.1  christos put_u32(void *vp, u_int32_t v)
    904   1.1  christos {
    905   1.1  christos 	u_char *p = (u_char *)vp;
    906   1.1  christos 
    907   1.1  christos 	p[0] = (u_char)(v >> 24) & 0xff;
    908   1.1  christos 	p[1] = (u_char)(v >> 16) & 0xff;
    909   1.1  christos 	p[2] = (u_char)(v >> 8) & 0xff;
    910   1.1  christos 	p[3] = (u_char)v & 0xff;
    911   1.1  christos }
    912   1.1  christos 
    913   1.9  christos void
    914   1.9  christos put_u32_le(void *vp, u_int32_t v)
    915   1.9  christos {
    916   1.9  christos 	u_char *p = (u_char *)vp;
    917   1.9  christos 
    918   1.9  christos 	p[0] = (u_char)v & 0xff;
    919   1.9  christos 	p[1] = (u_char)(v >> 8) & 0xff;
    920   1.9  christos 	p[2] = (u_char)(v >> 16) & 0xff;
    921   1.9  christos 	p[3] = (u_char)(v >> 24) & 0xff;
    922   1.9  christos }
    923   1.1  christos 
    924   1.1  christos void
    925   1.1  christos put_u16(void *vp, u_int16_t v)
    926   1.1  christos {
    927   1.1  christos 	u_char *p = (u_char *)vp;
    928   1.1  christos 
    929   1.1  christos 	p[0] = (u_char)(v >> 8) & 0xff;
    930   1.1  christos 	p[1] = (u_char)v & 0xff;
    931   1.1  christos }
    932   1.1  christos 
    933   1.1  christos void
    934   1.1  christos ms_subtract_diff(struct timeval *start, int *ms)
    935   1.1  christos {
    936   1.1  christos 	struct timeval diff, finish;
    937   1.1  christos 
    938   1.1  christos 	gettimeofday(&finish, NULL);
    939   1.1  christos 	timersub(&finish, start, &diff);
    940   1.1  christos 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
    941   1.1  christos }
    942   1.1  christos 
    943   1.1  christos void
    944   1.1  christos ms_to_timeval(struct timeval *tv, int ms)
    945   1.1  christos {
    946   1.1  christos 	if (ms < 0)
    947   1.1  christos 		ms = 0;
    948   1.1  christos 	tv->tv_sec = ms / 1000;
    949   1.1  christos 	tv->tv_usec = (ms % 1000) * 1000;
    950   1.1  christos }
    951   1.1  christos 
    952   1.8  christos time_t
    953   1.8  christos monotime(void)
    954   1.8  christos {
    955   1.8  christos 	struct timespec ts;
    956   1.8  christos 
    957   1.8  christos 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
    958   1.8  christos 		fatal("clock_gettime: %s", strerror(errno));
    959   1.8  christos 
    960   1.8  christos 	return (ts.tv_sec);
    961   1.8  christos }
    962   1.8  christos 
    963  1.13  christos double
    964  1.13  christos monotime_double(void)
    965  1.13  christos {
    966  1.13  christos 	struct timespec ts;
    967  1.13  christos 
    968  1.13  christos 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
    969  1.13  christos 		fatal("clock_gettime: %s", strerror(errno));
    970  1.13  christos 
    971  1.13  christos 	return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
    972  1.13  christos }
    973  1.13  christos 
    974   1.5  christos void
    975   1.5  christos bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
    976   1.5  christos {
    977   1.5  christos 	bw->buflen = buflen;
    978   1.5  christos 	bw->rate = kbps;
    979   1.5  christos 	bw->thresh = bw->rate;
    980   1.5  christos 	bw->lamt = 0;
    981   1.5  christos 	timerclear(&bw->bwstart);
    982   1.5  christos 	timerclear(&bw->bwend);
    983   1.5  christos }
    984   1.5  christos 
    985   1.5  christos /* Callback from read/write loop to insert bandwidth-limiting delays */
    986   1.5  christos void
    987   1.5  christos bandwidth_limit(struct bwlimit *bw, size_t read_len)
    988   1.5  christos {
    989   1.5  christos 	u_int64_t waitlen;
    990   1.5  christos 	struct timespec ts, rm;
    991   1.5  christos 
    992   1.5  christos 	if (!timerisset(&bw->bwstart)) {
    993   1.5  christos 		gettimeofday(&bw->bwstart, NULL);
    994   1.5  christos 		return;
    995   1.5  christos 	}
    996   1.5  christos 
    997   1.5  christos 	bw->lamt += read_len;
    998   1.5  christos 	if (bw->lamt < bw->thresh)
    999   1.5  christos 		return;
   1000   1.5  christos 
   1001   1.5  christos 	gettimeofday(&bw->bwend, NULL);
   1002   1.5  christos 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
   1003   1.5  christos 	if (!timerisset(&bw->bwend))
   1004   1.5  christos 		return;
   1005   1.5  christos 
   1006   1.5  christos 	bw->lamt *= 8;
   1007   1.5  christos 	waitlen = (double)1000000L * bw->lamt / bw->rate;
   1008   1.5  christos 
   1009   1.5  christos 	bw->bwstart.tv_sec = waitlen / 1000000L;
   1010   1.5  christos 	bw->bwstart.tv_usec = waitlen % 1000000L;
   1011   1.5  christos 
   1012   1.5  christos 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
   1013   1.5  christos 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
   1014   1.5  christos 
   1015   1.5  christos 		/* Adjust the wait time */
   1016   1.5  christos 		if (bw->bwend.tv_sec) {
   1017   1.5  christos 			bw->thresh /= 2;
   1018   1.5  christos 			if (bw->thresh < bw->buflen / 4)
   1019   1.5  christos 				bw->thresh = bw->buflen / 4;
   1020   1.5  christos 		} else if (bw->bwend.tv_usec < 10000) {
   1021   1.5  christos 			bw->thresh *= 2;
   1022   1.5  christos 			if (bw->thresh > bw->buflen * 8)
   1023   1.5  christos 				bw->thresh = bw->buflen * 8;
   1024   1.5  christos 		}
   1025   1.5  christos 
   1026   1.5  christos 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
   1027   1.5  christos 		while (nanosleep(&ts, &rm) == -1) {
   1028   1.5  christos 			if (errno != EINTR)
   1029   1.5  christos 				break;
   1030   1.5  christos 			ts = rm;
   1031   1.5  christos 		}
   1032   1.5  christos 	}
   1033   1.5  christos 
   1034   1.5  christos 	bw->lamt = 0;
   1035   1.5  christos 	gettimeofday(&bw->bwstart, NULL);
   1036   1.5  christos }
   1037   1.5  christos 
   1038   1.5  christos /* Make a template filename for mk[sd]temp() */
   1039   1.5  christos void
   1040   1.5  christos mktemp_proto(char *s, size_t len)
   1041   1.5  christos {
   1042   1.5  christos 	const char *tmpdir;
   1043   1.5  christos 	int r;
   1044   1.5  christos 
   1045   1.5  christos 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
   1046   1.5  christos 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
   1047   1.5  christos 		if (r > 0 && (size_t)r < len)
   1048   1.5  christos 			return;
   1049   1.5  christos 	}
   1050   1.5  christos 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
   1051   1.5  christos 	if (r < 0 || (size_t)r >= len)
   1052   1.5  christos 		fatal("%s: template string too short", __func__);
   1053   1.5  christos }
   1054   1.5  christos 
   1055   1.5  christos static const struct {
   1056   1.5  christos 	const char *name;
   1057   1.5  christos 	int value;
   1058   1.5  christos } ipqos[] = {
   1059   1.5  christos 	{ "af11", IPTOS_DSCP_AF11 },
   1060   1.5  christos 	{ "af12", IPTOS_DSCP_AF12 },
   1061   1.5  christos 	{ "af13", IPTOS_DSCP_AF13 },
   1062   1.7  christos 	{ "af21", IPTOS_DSCP_AF21 },
   1063   1.5  christos 	{ "af22", IPTOS_DSCP_AF22 },
   1064   1.5  christos 	{ "af23", IPTOS_DSCP_AF23 },
   1065   1.5  christos 	{ "af31", IPTOS_DSCP_AF31 },
   1066   1.5  christos 	{ "af32", IPTOS_DSCP_AF32 },
   1067   1.5  christos 	{ "af33", IPTOS_DSCP_AF33 },
   1068   1.5  christos 	{ "af41", IPTOS_DSCP_AF41 },
   1069   1.5  christos 	{ "af42", IPTOS_DSCP_AF42 },
   1070   1.5  christos 	{ "af43", IPTOS_DSCP_AF43 },
   1071   1.5  christos 	{ "cs0", IPTOS_DSCP_CS0 },
   1072   1.5  christos 	{ "cs1", IPTOS_DSCP_CS1 },
   1073   1.5  christos 	{ "cs2", IPTOS_DSCP_CS2 },
   1074   1.5  christos 	{ "cs3", IPTOS_DSCP_CS3 },
   1075   1.5  christos 	{ "cs4", IPTOS_DSCP_CS4 },
   1076   1.5  christos 	{ "cs5", IPTOS_DSCP_CS5 },
   1077   1.5  christos 	{ "cs6", IPTOS_DSCP_CS6 },
   1078   1.5  christos 	{ "cs7", IPTOS_DSCP_CS7 },
   1079   1.5  christos 	{ "ef", IPTOS_DSCP_EF },
   1080   1.5  christos 	{ "lowdelay", IPTOS_LOWDELAY },
   1081   1.5  christos 	{ "throughput", IPTOS_THROUGHPUT },
   1082   1.5  christos 	{ "reliability", IPTOS_RELIABILITY },
   1083   1.5  christos 	{ NULL, -1 }
   1084   1.5  christos };
   1085   1.5  christos 
   1086   1.5  christos int
   1087   1.5  christos parse_ipqos(const char *cp)
   1088   1.5  christos {
   1089   1.5  christos 	u_int i;
   1090   1.5  christos 	char *ep;
   1091   1.5  christos 	long val;
   1092   1.5  christos 
   1093   1.5  christos 	if (cp == NULL)
   1094   1.5  christos 		return -1;
   1095   1.5  christos 	for (i = 0; ipqos[i].name != NULL; i++) {
   1096   1.5  christos 		if (strcasecmp(cp, ipqos[i].name) == 0)
   1097   1.5  christos 			return ipqos[i].value;
   1098   1.5  christos 	}
   1099   1.5  christos 	/* Try parsing as an integer */
   1100   1.5  christos 	val = strtol(cp, &ep, 0);
   1101   1.5  christos 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
   1102   1.5  christos 		return -1;
   1103   1.5  christos 	return val;
   1104   1.5  christos }
   1105   1.5  christos 
   1106   1.6  christos const char *
   1107   1.6  christos iptos2str(int iptos)
   1108   1.6  christos {
   1109   1.6  christos 	int i;
   1110   1.6  christos 	static char iptos_str[sizeof "0xff"];
   1111   1.6  christos 
   1112   1.6  christos 	for (i = 0; ipqos[i].name != NULL; i++) {
   1113   1.6  christos 		if (ipqos[i].value == iptos)
   1114   1.6  christos 			return ipqos[i].name;
   1115   1.6  christos 	}
   1116   1.6  christos 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
   1117   1.6  christos 	return iptos_str;
   1118   1.6  christos }
   1119   1.6  christos 
   1120   1.9  christos void
   1121   1.9  christos lowercase(char *s)
   1122   1.9  christos {
   1123   1.9  christos 	for (; *s; s++)
   1124   1.9  christos 		*s = tolower((u_char)*s);
   1125   1.9  christos }
   1126   1.9  christos 
   1127   1.4      adam int
   1128   1.9  christos unix_listener(const char *path, int backlog, int unlink_first)
   1129   1.4      adam {
   1130   1.9  christos 	struct sockaddr_un sunaddr;
   1131   1.9  christos 	int saved_errno, sock;
   1132   1.4      adam 
   1133   1.9  christos 	memset(&sunaddr, 0, sizeof(sunaddr));
   1134   1.9  christos 	sunaddr.sun_family = AF_UNIX;
   1135   1.9  christos 	if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
   1136   1.9  christos 		error("%s: \"%s\" too long for Unix domain socket", __func__,
   1137   1.9  christos 		    path);
   1138   1.9  christos 		errno = ENAMETOOLONG;
   1139   1.9  christos 		return -1;
   1140   1.9  christos 	}
   1141   1.9  christos 
   1142   1.9  christos 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
   1143   1.9  christos 	if (sock < 0) {
   1144   1.9  christos 		saved_errno = errno;
   1145   1.9  christos 		error("socket: %.100s", strerror(errno));
   1146   1.9  christos 		errno = saved_errno;
   1147   1.9  christos 		return -1;
   1148   1.9  christos 	}
   1149   1.9  christos 	if (unlink_first == 1) {
   1150   1.9  christos 		if (unlink(path) != 0 && errno != ENOENT)
   1151   1.9  christos 			error("unlink(%s): %.100s", path, strerror(errno));
   1152   1.9  christos 	}
   1153   1.9  christos 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
   1154   1.9  christos 		saved_errno = errno;
   1155   1.9  christos 		error("bind: %.100s", strerror(errno));
   1156   1.9  christos 		close(sock);
   1157   1.9  christos 		error("%s: cannot bind to path: %s", __func__, path);
   1158   1.9  christos 		errno = saved_errno;
   1159   1.9  christos 		return -1;
   1160   1.9  christos 	}
   1161   1.9  christos 	if (listen(sock, backlog) < 0) {
   1162   1.9  christos 		saved_errno = errno;
   1163   1.9  christos 		error("listen: %.100s", strerror(errno));
   1164   1.9  christos 		close(sock);
   1165   1.9  christos 		unlink(path);
   1166   1.9  christos 		error("%s: cannot listen on path: %s", __func__, path);
   1167   1.9  christos 		errno = saved_errno;
   1168   1.9  christos 		return -1;
   1169   1.9  christos 	}
   1170   1.9  christos 	return sock;
   1171   1.4      adam }
   1172  1.13  christos 
   1173  1.13  christos /*
   1174  1.13  christos  * Compares two strings that maybe be NULL. Returns non-zero if strings
   1175  1.13  christos  * are both NULL or are identical, returns zero otherwise.
   1176  1.13  christos  */
   1177  1.13  christos static int
   1178  1.13  christos strcmp_maybe_null(const char *a, const char *b)
   1179  1.13  christos {
   1180  1.13  christos 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
   1181  1.13  christos 		return 0;
   1182  1.13  christos 	if (a != NULL && strcmp(a, b) != 0)
   1183  1.13  christos 		return 0;
   1184  1.13  christos 	return 1;
   1185  1.13  christos }
   1186  1.13  christos 
   1187  1.13  christos /*
   1188  1.13  christos  * Compare two forwards, returning non-zero if they are identical or
   1189  1.13  christos  * zero otherwise.
   1190  1.13  christos  */
   1191  1.13  christos int
   1192  1.13  christos forward_equals(const struct Forward *a, const struct Forward *b)
   1193  1.13  christos {
   1194  1.13  christos 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
   1195  1.13  christos 		return 0;
   1196  1.13  christos 	if (a->listen_port != b->listen_port)
   1197  1.13  christos 		return 0;
   1198  1.13  christos 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
   1199  1.13  christos 		return 0;
   1200  1.13  christos 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
   1201  1.13  christos 		return 0;
   1202  1.13  christos 	if (a->connect_port != b->connect_port)
   1203  1.13  christos 		return 0;
   1204  1.13  christos 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
   1205  1.13  christos 		return 0;
   1206  1.13  christos 	/* allocated_port and handle are not checked */
   1207  1.13  christos 	return 1;
   1208  1.13  christos }
   1209  1.13  christos 
   1210  1.14  christos /* returns 1 if bind to specified port by specified user is permitted */
   1211  1.14  christos int
   1212  1.14  christos bind_permitted(int port, uid_t uid)
   1213  1.14  christos {
   1214  1.14  christos 	if (port < IPPORT_RESERVED && uid != 0)
   1215  1.14  christos 		return 0;
   1216  1.14  christos 	return 1;
   1217  1.14  christos }
   1218  1.14  christos 
   1219  1.14  christos /* returns 1 if process is already daemonized, 0 otherwise */
   1220  1.14  christos int
   1221  1.14  christos daemonized(void)
   1222  1.14  christos {
   1223  1.14  christos 	int fd;
   1224  1.14  christos 
   1225  1.14  christos 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
   1226  1.14  christos 		close(fd);
   1227  1.14  christos 		return 0;	/* have controlling terminal */
   1228  1.14  christos 	}
   1229  1.14  christos 	if (getppid() != 1)
   1230  1.14  christos 		return 0;	/* parent is not init */
   1231  1.14  christos 	if (getsid(0) != getpid())
   1232  1.14  christos 		return 0;	/* not session leader */
   1233  1.14  christos 	debug3("already daemonized");
   1234  1.14  christos 	return 1;
   1235  1.14  christos }
   1236