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