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