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