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